I have four pieces of data I always want to keep together: 2 NSArrays and 2 ints. I thought a struct might be a good idea, but I get the "ARC does not allow objects in structs" error. What would be the best way to encapsulate the data? Using an NSDictionary?
2 Answers
Create a class with 4 properties. This allows for future growth by adding standard methods like isEqual: and making it work with NSCoding, etc. You can also add convenience constructors and other helpful methods as needed.
2 Comments
user1802143
1) Should this be a new, separate class or included as part of an existing one that uses it? 2) I only need one set of data as I just update it accordingly. Is a singleton pattern okay to use for this?
rmaddy
Create a separate class if it makes sense for your needs. This makes it easy to reuse. Using a singleton should only be used if you are 100% sure your whole app should only ever access a single instance of this class.
You can do it this way:
NSArray *arr1 = [[NSArray alloc] initWithObjects:@"apple",@"orange", nil];
NSArray *arr2 = [[NSArray alloc] initWithObjects:@"pine",@"pinnacle", nil];
NSInteger val1 = 1;
NSInteger val2 = 2;
NSMutableDictionary *dictTest = [[NSMutableDictionary alloc] init];
[dictTest setObject:arr1 forKey:@"arr1"];
[dictTest setObject:arr2 forKey:@"arr2"];
[dictTest setObject:[NSNumber numberWithInteger:val1] forKey:@"val1"];
[dictTest setObject:[NSNumber numberWithInteger:val2] forKey:@"val2"];
1 Comment
rmaddy
Use modern Objective-C.
NSArray1 *arr1 = @[ @"apple", @"orange"];. Then NSDictionary *dict = @{ @"arr1" : arr1, @"arr2" : arr2, @"val1" : @(val1), @"val2" : @(val2) };.