开发者

iphone/objective-c: using singleton class as a container for globals

So I'm finding that I'm using a singleton User class to access global variables throughout an iphone app. In some cases I use the instance in al开发者_StackOverflow社区most all the methods within a class. So in the first few lines of each method I have statement such as:

User *user = [User sharedManager];

This is obviously not a very DRY implementation. My question is: instead of repeating this statement in all the methods I need to access User can't I just instantiate this once, say in the initializer, and then set a property equal to this pointer such as:

-(id)init {
.....
self.sharedUser = [User sharedManager];
....
}

and then reference this property in each method instead of instantiating the singleton?


sure, you can do this. There might be (small) issues with code readability, but there's nothing wrong with this.


Why not just introduce a global that points to your singleton instead. Whilst its "less pure", you are trading off end-user performance. self.sharedUser.sharedValue will have exactly the same run-time cost as [[User sharedManager] sharedValue]

Dot notation for properties is about the stupidest thing that was ever added to Objective-C - it confuses the crap out of people who think its someway more efficient.

Now, if you meant self->sharedUser->sharedValue then you would be avoiding the property-method lookup and using two pointer-deferences instead - thats going to be about as fast as having globalUser->sharedValue, but has the added overhead of needing a new pointer in every instance of every class that wants to access the globals.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜