与 NSString 相关的问题
我有 1 NSString *abc = @"Hardik"; 我有 NSMutableArray *array; 现在我已经写了 [array addobject:abc];
然后我打印,NSLog(@"array = %@", array);
但我得到了 NULL 为什么? 我已经声明 NSMutableArray *array;在.ah文件中 我已经设置了 @property(nonatomic,retain)NSMutableArray *array; @合成数组;
我已经合成了它,但得到的值为 NULL 我无法理解吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您还需要初始化数组:
这是非常基本的东西。您是否阅读过“学习 Objective C 入门”了吗?
You also need to initialise your array:
This is pretty fundamental stuff. Have you read the "Learning Objective C Primer" yet?
听起来您实际上还没有分配
数组
。通常,您会在初始化程序中执行此操作。 (也不要忘记将release
添加到您的dealloc
方法中。)@synthesize
创建 getter 和 setter,但您仍然拥有自己处理对象的分配/解除分配。It sounds like you haven't actually allocated
array
. Generally, you would do this in your initializer. (Don't forget to add arelease
to yourdealloc
method, too.)@synthesize
creates the getter and setter, but you still have to handle allocating/deallocating the object yourself.听起来您的 NSMutableArray* 数组属性可能尚未初始化?
你能发布你的类初始化方法吗?
It sounds like your NSMutableArray* array property may not have been initialised?
Can you post your class init method?
要在类本身内触发合成访问器,您必须使用
self
。如果不这样做,您将绕过访问器方法直接访问属性的地址。您需要:这很重要的原因是合成方法通常也会初始化属性。合成数组方法的内部结构如下所示:
self.propertyName
实际上只是[self propertyName]
和self.propertyName=someValue
的简写> 只是[self setPropertyName:someValue]
的简写。在您至少调用一次
self.array
之前,数组属性不会初始化。然而,只是为了混淆事情,一旦你在初始化后调用了 self.array ,那么你就可以直接调用 array 。所以...
...有效,而相反只会返回一个空数组。
所以规则是:
(包括子类),只调用
propertyName
为您提供地址的属性,但不调用
getter/setter 访问器方法。
(包括子类),使用
self.propertyName
调用getter/setter 访问器方法但是
不直接访问属性。
实施例如
myClass.propertyName
调用getter/setter 访问器方法。
To trigger the synthesized accessor within a class itself, you must use
self
. If you don't, you access the attribute's address directly bypassing the accessor methods. You need:The reason this is important is that the synthesized methods usually also initialize the property. The internals of the synthesize array method would look something like:
self.propertyName
is really just shorthand for[self propertyName]
andself.propertyName=someValue
is just shorthand for[self setPropertyName:someValue]
.Until you call
self.array
at least once, the array property is not initialized.However, just to confuse things, once you have called
self.array
once it is initialized so you can just callarray
directly. So......works while the converse would return just an empty array.
So the rules are:
(including subclasses), calling just
propertyName
gives you the addressof the property but does not call
the getter/setter accessor methods.
(including subclasses), using
self.propertyName
calls thegetter/setter accessor methods but
does not access attribute directly.
implementation e.g.
myClass.propertyName
calls thegetter/setter accessor methods.