I have 1 NSString *abc = @"Hardik"; i have NSMutableArray *array; now i had written [array addobject:abc];
then i'm printing,NSLog(@"array = %@", array);
but i'm getting NULL why? I have declared NSMutableArr开发者_开发知识库ay *array; in a.h file i had set @property(nonatomic,retain)NSMutableArray *array; @synthesize array;
and i have synthesize it but getting value NULL I'm not able to understand it?
You also need to initialise your array:
array = [[NSMutableArray alloc] initWithCapacity:10];
This is pretty fundamental stuff. Have you read the "Learning Objective C Primer" yet?
It sounds like you haven't actually allocated array
. Generally, you would do this in your initializer. (Don't forget to add a release
to your dealloc
method, too.) @synthesize
creates the getter and setter, but you still have to handle allocating/deallocating the object yourself.
It sounds like your NSMutableArray* array property may not have been initialised?
Can you post your class init method?
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:
NSString *abc = @"Hardik";
[self.array addobject:abc];
NSLog(@"array = %@", self.array);
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:
-(NSArray *) array{
if (array!=nil) {
return array;
}
array=[[NSMutableArray alloc] initWithCapacity:1];
return array;
}
self.propertyName
is really just shorthand for [self propertyName]
and self.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 call array
directly. So...
[self.array addObject:abc];
NSLog(@"array = %@", array);
...works while the converse would return just an empty array.
So the rules are:
- Within a class implementation
(including subclasses), calling just
propertyName
gives you the address of the property but does not call the getter/setter accessor methods. - Within a class implementation
(including subclasses), using
self.propertyName
calls the getter/setter accessor methods but does not access attribute directly. - From outside the class
implementation e.g.
myClass.propertyName
calls the getter/setter accessor methods.
精彩评论