NSArray life cycle
I create an NSArray object in .h file:
NSArray *tempArray;
and than I alloc it in .m file in viewDidLoad() metho开发者_开发百科d:
tempArray = [[NSArray alloc] init]; //initilaize
tempArray = [connect connectSeriesJSonBack]; //fill it (I try it works)
But I want to use this array in another method like:
- (void)scrollViewDidEndDecelerating:(UIScrollView *)_scrollView
How can i organize array lifecycle because I use alloc, retain etc. no way the reach array data again.
Don't release the array in the method, and instead release it in the dealloc method -- that way you can use it other places.
Otherwise there is another problem here.
Here you create a retained, empty, immutable NSArray
tempArray = [[NSArray alloc] init];
And now you overwrite the pointer to that retained instance, yay, you just leaked an NSArray
tempArray = [connect connectSeriesJSonBack];
And that method should be returning an autoreleased NSArray. Which will be automatically released and go away once you hit an event loop.
You should do something like this
-(void)whereverThisIs {
// Do not retain here if connectSeriesJSonBack returns a retained instance
tempArray = [[connect connectSeriesJSonBack] retain];
}
-(void)dealloc {
[tempArray release];
}
-(void)anotherMethod {
if ( tempArray ) { // Do things }
}
Your second assignment for tempArray will generate a memory leak because the allocation can never be accessed again. connectSeriesJSonBAck
will probably return a autoreleased NSArray
. If you want to keep referencing it outside of the current scope then you should retain it:
instead of:
tempArray = [[NSArray alloc] init]; //initilaize
tempArray = [connect connectSeriesJSonBack]; //fill it (I try it works)
do
tempArray = [connect connectSeriesJSonBack];
[tempArray retain];
and add [tempArray release]
in your class' dealloc
method.
If you want to access the same array within the class then you can probably try making it a class variable so that its members can be accessed throughout the class.
I suggest to declar it in implemantation like
@implementation YourViewController
NSMutableArray *mutableExample;
// or
NSArray *example;
then in -()viewdidload
alloc it like mutableExample = [[[NSMutableArray alloc] init]retain];
or just example = [[NSArray alloc] init];
and the you can use it every where.do not forget to release it!!!
hope it helps if something is unclear ask it in the comment
wblade
If you return an autoreleased array from the function [connect connectSeriesJSonBack];
than your tempArray
will be have a return count of 0 after the viewDidLoad
method.
There are 2 approaches how to make it work
1) use an NSMutableArray
object and add the objects
tempArray = [[NSMutableArray alloc] init];
[tempArray addObjectsFromArray:[connect connectSeriesJSonBack]];
2) retain the returned array
tempArray = [[connect connectSeriesJSonBack] retain];
精彩评论