Reputation: 1373
Say I want to have an item that holds a string as a value to a key, using a dictionary I would write:
[NSDictionary dictionaryWithObject:@"someString" forKey:@"stringKey"];
I'm asking how to do this without a dictionary (ambiguous, the programmer needs to know the key) or an object (overkill for this thin object, no need for methods), something more in the lines of structs, I tried structs before, but I haven't seen any struct in iOS that uses chars
as struct items, so I'm not sure that this is the way to go. The result should be similar to this:
replacement.key = value;
Any thoughts?
Upvotes: 2
Views: 728
Reputation: 11834
Why don't you just use the dictionary but create a set of NSString constants that will work as the key? Then there will be less ambiguity.
For example consider Apple's key constant used for retrieving a localized string from a NSError's userInfo dictionary NSLocalizedDescriptionKey
. Many other keys are used as well to retrieve specific parts of information and because these keys are constants, they're easy to use in Xcode (autocompletion). Another example of using string constants to retrieve values out of an NSDictionary could be NSFileManager.
Additionally, just using an object should be fine as well, in most cases the 'overhead' should be negligible - certainly not anything a user would notice. At the very least, please don't try to prematurely optimize your code for situations that might ever happen in the very far future ...
Upvotes: 0
Reputation: 4413
A thin object with @property
and @synthesize
will save you any pain of creating methods. All instance variable will be created and modified without any code of yours.
Such an object definition would hardly be larger than a struct, and, being a subclass of NSObject
, it can be put in any array or other framework containers which only accept NSObject
subclasses. You won't be able to do that with structs.
If you use XCode 4.4 (for Mac development) or 4.5 (for iOS), you'll even be able to drop @synthesize
and only have @property
.
Only if you're really tight on performance and need to get away from NSObject
hierarchy you should be considering dropping it and using C structs.
Upvotes: 1
Reputation: 299345
A small data object is seldom overkill unless you have a very specialized problem. For example, if you had many thousands of these objects, and particularly if you needed to create and destroy them quickly, and you had profiled your app and discovered that the objects themselves were a real problem, then you should consider not using simple data objects. But in the general case, you should use simple data objects.
Upvotes: 1
Reputation: 8180
I am not sure, if it what you want, but you can use a struct
:
typedef struct {
__unsafe_unretained NSString* key;
...
} foo;
foo bar;
NSString* foobar = @"Hello";
bar.key = foobar;
Attention, there is no reason for ARC not to dispose this value. But if you have a strong reference to the value, you can use it.
Upvotes: 1