NSCoder - archive pointer?

I have an objective-c class that contains a pointer to another class. I want to archive an instance of this class through NSCoder:

@interface Barn
{
    int m_numHorses;

    // Barn does not allocate this instance, it just points to it.
    Farmer* m_pFarmer;
}
@end

...

- (void)encodeWithCoder:(NSCoder *)encoder
{
    [encoder encodeInt:m_numHorses forKey:@"numHorses"];
    [encoder encode?:m_pFarmer forKey:@"pFarmer"];
}

- (void) setPointer:(Farmer*)pFarmer
{
    m_pFarmer = pFarmer;
}

How can I archive the m_pFarmer pointer? This does not make any sense to me, since all this is an address, and I do not see that NSCoder can serialize to disk for you so that it knows how to restore the link later when deserializing?

+3
source share
5 answers

You cannot directly encode the pointer, because when you unload objects, the value of the pointer will be completely different. I mean, you can save it using

encodeValueOfObjCType:@encode(id) at:&m_pFarmer 

, ; , , .

Barn Farmer, Barn ; Farmer, . , Barn .

- Farmer, ? Barn findMyFarmer, FarmerOwner , . (, farmerID ivar Farmer?). -[NSObject awakeAfterUsingCoder:(NSCoder *)] Barn, .

, . documentation , , .

NSArchiver NSKeyedArchiver , ( encodeConditionalObject:), , - . " .". , Farmer , , Barn - , .

, .

+6

encodeObject: NSCoding Farmer, .

+3

, BJ.

, . , , , . . , . ObjC , ++. , .

, ? , ? ? ? , .

+3

, ( , Farmer , ), NSInteger.

. [encoder encodeInteger:(NSInteger)m_pFarmer forKey:@"pFarmer"];

, , , Farmer , .

0

- . UUID ( ) ,

var uniqueIdentifier: String = NSUUID().UUIDString

UUID , NSCoding.

, UUID ( "" , UUID). UUID NSCoding. , .

, CoreData, ...

EDIT: , NSCoding. , ( ). , NSCoding , "" . . , ( ), ( %). , ( ) . , NSCoding.

0

Source: https://habr.com/ru/post/1708523/


All Articles