You cannot use NSUserDefaults
for a custom class. From the documentation:
The
NSUserDefaults
class provides convenience methods for accessing
common types such as floats, doubles, integers, Booleans, and URLs. A
default object must be a property list, that is, an instance of (or
for collections a combination of instances of):NSData
,NSString
,
NSNumber
,NSDate
,NSArray
, orNSDictionary
. If you want to store any
other type of object, you should typically archive it to create an
instance ofNSData
.
Try using NSData
. For example, to load custom objects into an array, you can do
NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
NSData *dataRepresentingSavedArray = [currentDefaults objectForKey:@"savedArray"];
if (dataRepresentingSavedArray != nil)
{
NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingSavedArray];
if (oldSavedArray != nil)
objectArray = [[NSMutableArray alloc] initWithArray:oldSavedArray];
else
objectArray = [[NSMutableArray alloc] init];
}
To archive the data, use:
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:objectArray] forKey:@"savedArray"];
This will all work so long as your custom object complies with the NSCoding
protocol:
- (void)encodeWithCoder:(NSCoder *)coder;
{
[coder encodeObject:label forKey:@"label"];
[coder encodeInteger:numberID forKey:@"numberID"];
}
- (id)initWithCoder:(NSCoder *)coder;
{
self = [[CustomObject alloc] init];
if (self != nil)
{
label = [coder decodeObjectForKey:@"label"];
numberID = [coder decodeIntegerForKey:@"numberID"];
}
return self;
}
ABRecord
is an opaque C type, so it’s not an object in the sense of Objective-C. That means you can not extend it, you can not add a category on it, you can not message it. The only thing you can do is call functions described in ABRecord
Reference with the ABRecord
as a parameter.
You could do two things to be able to keep the information referenced by the ABRecord
around:
-
Get the
ABRecord
sid
byABRecordGetRecordID()
. TheABRecordID
is defined as int32_t so you can cast it to anNSInteger
and store it wherever you like. You can later get the record back fromABAddressBookGetPersonWithRecordID()
orABAddressBookGetGroupWithRecordID()
. However, the record could be changed or even deleted by the user or another app meanwhile. -
Copy all values inside the record to a standard
NSObject
subclass and useNSCoding
as discussed above to store it. You will then, of course, not benefit from changes or additions to the record the user could have made.