views:

379

answers:

2

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 almost 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?

+2  A: 

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

Ben Gottlieb
Cool, thanks thats what I thought. ALso I think the readability issues would be dwarfed by the non-DRYness of the other approach
ennuikiller
I cannot see the benefit of it. `[[User sharedManager] doSomething]` is probably just as fast as `[self.sharedUser doSomething]`.
Georg
@Georg. I'm more concerned about setting or getting the globals: self.sharedUser.sharedValue = someValue; is certainly more concise and efficient than [User sharedManager].sharedValue = someValue;
ennuikiller
+1  A: 

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.

Jeff Laing