NSMutableArray 在 init 中创建后为空(带代码)
Posted
技术标签:
【中文标题】NSMutableArray 在 init 中创建后为空(带代码)【英文标题】:NSMutableArray empty after created in init (with code) 【发布时间】:2012-04-18 18:23:39 【问题描述】:@property (nonatomic, strong) NSMutableArray *authorMutableArray;
- (id)init
self = [super init];
if (self)
self.authorMutableArray = [[NSMutableArray alloc] initWithObjects:@"First Row", @"Second Row", nil];
for (NSString *string in authorMutableArray)
NSLog(@"String: %@", string);
NSLog(@"Init in Add Model with Author count:%i", [authorMutableArray count]);
访问属性的示例。 NSLog 始终显示计数为 0。
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
if (indexPath.section == 0)
if (indexPath.row == [self.addModel.authorMutableArray count] - 1 )
NSLog(@"count of %i", [self.addModel.authorMutableArray count]);
return UITableViewCellEditingStyleInsert;
else
return UITableViewCellEditingStyleDelete;
else
return UITableViewCellEditingStyleNone;
我在 init 中创建的数组没有保持它的值超过这个方法。有什么理由吗? for 循环将显示数组中的两个对象。如果我在调用 init 方法后尝试询问此问题,则数组为空。
更新:感谢大家的时间和眼睛。我忘记在 init 方法中返回 self。
【问题讨论】:
如何声明 authormutablearray 属性 它是常规合成属性。 @WDyson Warren 的意思是,您使用什么说明符?strong
, weak
, assign
?另外,你之后如何访问数组?你能给我们看一下代码吗?
我会更新OP,它很强大。
在您的editingStyleForRowAtIndexPath
方法中,检查addModel
是否也不是零。
【参考方案1】:
init 方法不应该返回 self 吗?
【讨论】:
是的,确实如此。我在同一个 init 方法中创建了 4 个 NSString 属性,我只是在这个例子中排除了它们。他们都工作得很好。为什么数组是唯一不保存数据的?【参考方案2】:在你的类的接口文件(.h 文件)中声明如下:
@interface Your_Class_Name : UIViewController
NSMutableArray *authorMutableArray;
@property (nonatomic, strong) NSMutableArray *authorMutableArray;
//i dont know why you prefered strong, chose retain and try again please
【讨论】:
strong
相当于 ARC 下的 retain
。它们在各自的内存管理系统中具有等效的语义。也不必单独声明 ivar;它是由@synthesize
创建的。
@lulius,你会使用哪个数组,强还是保留?
copy
,实际上,对于具有可变对应物的类,但strong
和retain
之间的选择仅取决于您是否使用ARC。
ARC 强大,否则保留?你所说的可变对应物是什么意思?我只是想确保我完全理解。
@WDy 是的,strong
在 ARC 下。可变对应含义NSArray
/NSMutableArray
、NSString
/NSMutableString
、NSIndexSet
/NSMutableIndexSet
,等等。如果将可变实例传递给您的 setter,则原始所有者可以更改它,除非您获取副本,这可能会产生令人惊讶的结果。围绕这一点有一些更深入的问题。【参考方案3】:
我们在这里不是在处理 C++ 或 Java,对象 MUST
的 -init
方法返回一个值。
这个怪癖实际上允许一些非常有趣的东西,例如。以下:
-(id) init
NSLog(@"Creating new instance of singleton object...");
#if __has_feature(objc-arc)
self = singleton_instance;
#else
[self release];
self = [singleton_instance retain];
#endif
return self;
它还允许类“摆姿势”,允许您准确跟踪特定类的对象何时初始化(这个答案的主题太深了)。
【讨论】:
以上是关于NSMutableArray 在 init 中创建后为空(带代码)的主要内容,如果未能解决你的问题,请参考以下文章