开发者

NSArray become empty after viewDidLoad

I created an object and there is an array in it

question.h

NSInteger num;
.....

NSArray * q;

-(questions*) a1:开发者_JAVA技巧(NSString*) a1 a2:(NSString*) a2 a3:(NSInteger) a3;

@property(nonatomic,retain) NSArray *q;

question.m

-(questions*) a1:(NSString*) a1 a2:(NSString*) a2 a3:(NSInteger) a3{
    self = [super init];

    if(self){
        q = [NSArray arrayWithObjects:a1,a2,nil];
        num = a3;
        return self;
    }

    return nil;
}

and here comes the question: I am using the object question in another object call answer in answer.m.

I called the constructor in the viewDidLoad function and display those values in the array.

It displays it normally.

However, when I try to access the array of the object, it crashes, I can't even check the length of the array.

However, I was able to display the value of the NSInteger (num) of the object.

What's wrong with this?


arrayWithObjects is autoreleased, you need to retain it or use the normal alloc / init version....

q = [[NSArray alloc] initWithObjects:a1, a2, nil]; 


As Simon says, your NSArray object is been autoreleased when the constructor finishes. If you follow this link, you'll notice that there are two ways for creating an object:

- (void)printHello {
    NSString *string;
    string = [[NSString alloc] initWithString:@"Hello"];
    NSLog(@"%@", string);
    [string release];
}

where you become in the owner of string object and then you have to release it. Or,

- (void)printHello {
    NSString *string;
    string = [NSString stringWithFormat:@"Hello"];
    NSLog(@"%@", string);
}

where the object is created but you don't need to release it because when the method printHello finishes, it will be sent to the autorelease pool. So, with NSArray's its the same, if you need to use the object out of the method, then use the first way with alloc + init, else you can use the other kind of methods.


try below code. ur a1,a2,a3 objects are getting autorelease objects you just retain and load into NSArray(name q)`

 -(questions*) a1:(NSString*) a1 a2:(NSString*) a2 a3:(NSInteger) a3{

 self = [super init];

if(self){
   [a1 retain];
   [a2 retain];
    [a3 retain];

    q = [NSArray arrayWithObjects:a1,a2,nil];
    num = a3;
    return self;
}

return nil;

}`

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜