开发者

Want to create a container class which will only exist once

开发者 https://www.devze.com 2023-01-20 22:53 出处:网络
I want to make a class that can hold settings for my app. Its pretty basic. I will access it from a few different classes, but only want 1 version of this container class to exist so they all see the

I want to make a class that can hold settings for my app. Its pretty basic. I will access it from a few different classes, but only want 1 version of this container class to exist so they all see the same data.

Is there something special i need to flag for this?

Here is what I've done so far: Filters.h

#import <Foundation/Foundation.h>
@interface Filters : NSObject 
{
    NSString    *fuelType;
}
@property (nonatomic, copy) NSString *fuelType;
@end

Filters.m

#import "Filters.h"
@implementation Filters
@synthesize fuelType;
@end

Is there some flag i need to use when i alloc an instance of this 开发者_JAVA百科class or how should I work this if I need to access the fuelType value from 2 different classes?

Thanks -Code


For global application settings a better way would be to use NSUserDefaults or if you want to store data for use you should look up using core data and sqlite.

Lastly, if you want to go for ease of use you could do a core data style app delegate class and grab it by using:

[[[UIApplication sharedApplication] delegate] myClass] that way you'll always have that version of the class.


You need a singleton: you can create your singleton by your own or use AppDelegate object which is an object that is always alive and never released while your application in the frontground (just put the vars needed there and initialize them dynamically).

Here are some links on how to create a singleton. Cocoa fundamental Guide: Creating a Singleton and CocoaDev Singleton Pattern


What you're looking for is a singleton. Most people advise against using singletons though as it is often considered "dirty". See "Singleton" in this apple doc to learn more about it.

0

精彩评论

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

关注公众号