当前位置: 动力学知识库 > 问答 > 编程问答 >

iphone - Passing an array between classes - strange error?

问题描述:

So I am creating and populating an array in Class A - then in Class B I call a method of class A to get the array

ClassA.h

-(NSMutableArray*)getArray

ClassA.m

-(NSMutableArray* )getFeedsArray

{

NSMutableArray *myArray;

if (!myArray)

{

myArray = [[NSMutableArray alloc]init];

[myArray addObject: @"hello"];

}

NSLog (@"Feeds array: %d", [myArray count ]);

return myArray;

}

}

Then in Class B - I do this:

ClassB.m

-(void)loadData

{

ClassA *classA = [[ClassA alloc]init];

NSMutableArray *mutableArray = [classA getFeedsArray];

NSLog (@"Items in Array: %d", [mutableArray count]);

}

The above works perfectly - array counts show 1, which is what the test should do.

However, when I do this:

in classA.m

-(NSMutableArray* )getFeedsArray

{

NSLog (@"Feeds array: %d", [feedsDownload count ]);

return feedsDownload;

}

The count is zero.

So I checked the feedDownload array in another method inside of ClassA.m that gets called before the getFeedsArray method does and it returns the correct value from that method.

However, when getFeedsArray is called from ClassB.m - the array count is zero. But it is only zero with the second version of the getFeedsArray code:

So if I do this and don't touch any other code:

-(NSMutableArray* )getFeedsArray

{

NSMutableArray *myArray;

if (!myArray)

{

myArray = [[NSMutableArray alloc]init];

[myArray addObject: @"hello"];

}

NSLog (@"Feeds array: %d", [myArray count ]);

return myArray;

}

Results:

Feeds array: 1 (from ClassA.m otherMethod) - otherMethod calls getFeedsArray method.

Feeds array:1

Items in Array: 1 (Inside ClassB.m)

If I then change the code like this:

-(NSMutableArray* )getFeedsArray

{

NSLog (@"Feeds array: %d", [feedsDownload count ]);

return feedsDownload;

}

Results:

Feeds array:1 (from ClassA.m otherMethod) - otherMethod calls getFeedsArray method.

Feeds array:0

Items in Array: 0 (Inside ClassB.m)

So it seems the second call to getFeedsArray gives me a zero count of my array.

Sorry but, WTH is happening here and what am I missing??

Thanks!

分享给朋友:
您可能感兴趣的文章:
随机阅读: