C array of Objective C objects
I'm trying to create a C array of objective C NSStrings using malloc. I'm not doing it right, but I don't think I'm far off. Maybe someone can point me in the right direction. Let's say we want 5 strings in our array for the sake of argument.
Interface:
开发者_如何转开发@interface someObject : NSObject {
NSString **ourArray;
}
@property () NSString **ourArray;
@end
Implementation:
@implementation someObject
@synthesize ourArray;
-(id)init {
if((self = [super init])) {
self->ourArray = malloc(5 * sizeof(NSString *));
}
return self;
}
-(NSString *)getStringAtPos3 {
if(self.ourArray[3] == nil) {
self.ourArray[3] = @"a string";
}
return self.ourArray[3];
}
@end
When I set a breakpoint in getStringAtPos3 it doesn't see the array element as nil so it never goes into the if statement.
malloc
ing an array of pointers is done as follows:
self->ourArray = malloc(5 * sizeof(NSString *));
if (self->ourArray == NULL)
/* handle error */
for (int i=0; i<5; i++)
self->ourArray[i] = nil;
malloc
doesn't make guarantees about the contents of the returned buffer, so set everything to nil
explicitly. calloc
won't help you here, as a zero pattern and nil
/NULL
aren't the same thing.
Edit: even though zero and null may be the same on i386 and arm, they are not the same conceptually, just like NULL
and nil
are strictly not the same. Preferably, define something like
void *allocStringPtrs(size_t n)
{
void *p = malloc(sizeof(NSString *));
if (p == NULL)
// throw an exception
for (size_t i=0; i<n; i++)
p[i] = nil;
return p;
}
One issue is this:
self->ourArray = malloc(5 * sizeof(NSString *)); // notice the sizeof()
I figured out the problem - I should have been using calloc, not malloc. While malloc simply allocates the memory, calloc
contiguously allocates enough space for count objects that are size bytes of memory each and returns a pointer to the allocated memory. The allocated memory is filled with bytes of value zero.
This means you get an array of nil objects essentially as in objective c 0x0 is the nil object.
精彩评论