best way to keep array's in code
Dear all. I need to keep some temporary information in code. When i acc开发者_高级运维ess to it, i make instant copy of my class, receive result as MutableArray, but i have to using this array in other method's of code. I don't like to make instant copy of my class again, bcs this take memory and processor time, but i have to using rest of array in other methods. Currently i keep it in array controller, but i like to find other better way. In some reasons i don't like to send pointer to this MutableArray as method's parameter. ProjectArrays.h:
#import <Cocoa/Cocoa.h>
@interface ProjectArrays : NSObject {
NSMutableArray *myMutableArray;
}
@property (nonatomic, retain) NSMutableArray *myMutableArray;
+(ProjectArrays *)sharedProjectArrays;
@end
ProjectArrays.m:
#import "ProjectArrays.h"
#import "SynthesizeSingleton.h"
@implementation ProjectArrays
SYNTHESIZE_SINGLETON_FOR_CLASS(ProjectArrays)
@synthesize myMutableArray;
- (void)dealloc {
// Clean-up code here.
[myMutableArray release];
[super dealloc];
}
@end
AppDelegate.m:
[[ProjectArrays sharedProjectArrays].myMutableArray addObject:@"Test"];
NSLog (@"This is test first point:%@",[[ProjectArrays sharedProjectArrays].myMutableArray objectAtIndex:0]);
2010-11-21 19:26:18.636 snow[14523:a0f] This is test first point:(null)
looks like code can't care objects.
Try using singleton pattern. Create some singleton class and keep there environmental variables.
Here is useful header file: http://snipplr.com/view/32737/synthesizesingleton-definition-header/
It will help you to create singletons promptly.
EDITED:
Here is a singleton you'd like to use
//YourSingletonClassName.h
#import <Foundation/Foundation.h>
@interface YourSingletonClassName : NSObject {
NSMutableArray *myMutableArray;
}
@property (nonatomic, retain) NSMutableArray *myMutableArray;
+ (YourSingletonClassName *)sharedYourSingletonClassName;
@end
//YourSingletonClassName.m
#import "YourSingletonClassName.h"
#import "SynthesizeSingleton.h"
@implementation YourSingletonClassName
SYNTHESIZE_SINGLETON_FOR_CLASS(YourSingletonClassName)
@synthesize myMutableArray;
- (id) init
{
self = [super init];
if (self != nil) {
self.myMutableArray = [NSMutableArray new];
}
return self;
}
- (void) dealloc {
[myMutableArray release];
[super dealloc];
}
@end
You can call YourSingletonClassName
anywhere by [YourSingletonClassName sharedYourSingletonClassName];
, you shouldn't alloc/init it, e.g:
[[YourSingletonClassName sharedYourSingletonClassName].myMutableArray addObject:@"some_object_to_add"];
Please google for singleton pattern and dig through obj c conceptions.
精彩评论