### Implement NSCopying and Equality in Objective-C Source: https://context7.com/ibireme/yymodel/llms.txt Use YYModel's model methods to automatically implement NSCopying, hash, isEqual, and description protocols for custom models. ```objc @interface Person : NSObject @property NSString *name; @property NSUInteger age; @property NSString *email; @end @implementation Person - (id)copyWithZone:(NSZone *)zone { return [self yy_modelCopy]; } - (NSUInteger)hash { return [self yy_modelHash]; } - (BOOL)isEqual:(id)object { return [self yy_modelIsEqual:object]; } - (NSString *)description { return [self yy_modelDescription]; } @end // Copy model Person *person1 = [Person new]; person1.name = @"John"; person1.age = 30; person1.email = @"john@example.com"; Person *person2 = [person1 copy]; // person2 is a deep copy with same values // Equality comparison Person *person3 = [Person new]; person3.name = @"John"; person3.age = 30; person3.email = @"john@example.com"; BOOL isEqual = [person1 isEqual:person3]; // YES // Use in collections NSSet *personSet = [NSSet setWithArray:@[person1, person3]]; // Set contains only 1 person (duplicates merged via hash/isEqual) // Debug description NSLog(@"%@", person1); // Prints formatted property list ``` -------------------------------- ### Implement NSCoding Support in Objective-C Source: https://context7.com/ibireme/yymodel/llms.txt Enable automatic archiving and unarchiving by delegating NSCoding methods to YYModel's internal helpers. Ensure the class conforms to the NSCoding protocol. ```objc @interface Settings : NSObject @property NSString *username; @property NSInteger fontSize; @property BOOL darkMode; @property CGSize windowSize; @end @implementation Settings - (void)encodeWithCoder:(NSCoder *)aCoder { [self yy_modelEncodeWithCoder:aCoder]; } - (instancetype)initWithCoder:(NSCoder *)aDecoder { self = [super init]; return [self yy_modelInitWithCoder:aDecoder]; } @end // Archive model to data Settings *settings = [Settings new]; settings.username = @"john"; settings.fontSize = 14; settings.darkMode = YES; settings.windowSize = CGSizeMake(800, 600); NSData *archivedData = [NSKeyedArchiver archivedDataWithRootObject:settings]; // Unarchive model from data Settings *restored = [NSKeyedUnarchiver unarchiveObjectWithData:archivedData]; // restored.username = @"john" // restored.fontSize = 14 // restored.darkMode = YES // restored.windowSize = {800, 600}" ``` -------------------------------- ### Custom Property Mapping with Key Paths and Fallbacks Source: https://context7.com/ibireme/yymodel/llms.txt Implement `modelCustomPropertyMapper` to map model properties to different JSON keys, including nested keys using paths and multiple fallback keys for flexibility. ```objc @interface Book : NSObject @property NSString *name; @property NSInteger page; @property NSString *desc; @property NSString *bookID; @end @implementation Book + (NSDictionary *)modelCustomPropertyMapper { return @{ @"name" : @"n", // Simple key mapping @"page" : @"p", // Simple key mapping @"desc" : @"ext.desc", // Key path for nested value @"bookID" : @[@"id", @"ID", @"book_id"] // Multiple fallback keys }; } @end // JSON with different key names NSString *json = @"{\"n\":\"Harry Potter\",\"p\":256,\"ext\":{\"desc\":\"A great book\"},\"ID\":100010}"; Book *book = [Book yy_modelWithJSON:json]; // book.name = @"Harry Potter" // book.page = 256 // book.desc = @"A great book" // book.bookID = @"100010" ``` -------------------------------- ### Implement Dynamic Class Selection in Objective-C Source: https://context7.com/ibireme/yymodel/llms.txt Override modelCustomClassForDictionary to return the appropriate subclass based on dictionary keys. This is essential for handling polymorphic JSON structures. ```objc @interface Shape : NSObject @property NSString *name; @end @interface Circle : Shape @property CGFloat radius; @end @implementation Circle @end @interface Rectangle : Shape @property CGFloat width; @property CGFloat height; @end @implementation Rectangle @end @implementation Shape + (Class)modelCustomClassForDictionary:(NSDictionary *)dictionary { if (dictionary[@"radius"]) { return [Circle class]; } else if (dictionary[@"width"]) { return [Rectangle class]; } return [Shape class]; } @end @interface Canvas : NSObject @property NSArray *shapes; @end @implementation Canvas + (NSDictionary *)modelContainerPropertyGenericClass { return @{@"shapes": [Shape class]}; } @end // JSON with mixed shape types NSString *json = @"{\"shapes\":[{\"name\":\"Circle1\",\"radius\":10},{\"name\":\"Rect1\",\"width\":20,\"height\":15}]}"; Canvas *canvas = [Canvas yy_modelWithJSON:json]; // canvas.shapes[0] is Circle instance with radius=10 // canvas.shapes[1] is Rectangle instance with width=20, height=15 Circle *circle = (Circle *)canvas.shapes[0]; // circle.radius = 10" ``` -------------------------------- ### Property Whitelist and Blacklist Source: https://context7.com/ibireme/yymodel/llms.txt Restricts which properties are processed during model conversion using whitelist or blacklist methods. ```objc @interface User : NSObject @property NSString *name; @property NSString *email; @property NSString *password; @property NSString *secretToken; @property NSUInteger age; @end @implementation User // Exclude sensitive properties from conversion + (NSArray *)modelPropertyBlacklist { return @[@"password", @"secretToken"]; } @end // Alternative: only include specific properties @interface PublicProfile : NSObject @property NSString *name; @property NSString *email; @property NSString *avatar; @property NSString *internalId; @end @implementation PublicProfile + (NSArray *)modelPropertyWhitelist { return @[@"name", @"avatar"]; // Only these properties will be converted } @end // Usage NSString *json = @"{\"name\":\"John\",\"email\":\"john@test.com\",\"password\":\"secret123\",\"age\":25}"; User *user = [User yy_modelWithJSON:json]; // user.name = @"John" // user.password = nil (blacklisted, not converted) NSDictionary *output = [user yy_modelToJSONObject]; // {"name":"John","email":"john@test.com","age":25} // password and secretToken are excluded ``` -------------------------------- ### Simple JSON to Model Conversion Source: https://github.com/ibireme/yymodel/blob/master/README.md Convert JSON data to a model object using yy_modelWithJSON:. Convert a model object back to a JSON object using yy_modelToJSONObject:. ```objc // JSON: { "uid":123456, "name":"Harry", "created":"1965-07-31T00:00:00+0000" } // Model: @interface User : NSObject @property UInt64 uid; @property NSString *name; @property NSDate *created; @end @implementation User @end // Convert json to model: User *user = [User yy_modelWithJSON:json]; // Convert model to json: NSDictionary *json = [user yy_modelToJSONObject]; ``` -------------------------------- ### Implement Custom Transform Hooks in Objective-C Source: https://context7.com/ibireme/yymodel/llms.txt Use these methods to modify input dictionaries, validate data, or perform custom type conversions during the JSON-to-model and model-to-JSON lifecycle. Returning NO from validation methods will cause the model transformation to fail. ```objc @interface Event : NSObject @property uint64_t eventId; @property NSString *content; @property NSDate *timestamp; @end @implementation Event // Called before transformation - modify input dictionary - (NSDictionary *)modelCustomWillTransformFromDictionary:(NSDictionary *)dic { NSMutableDictionary *mutableDic = [NSMutableDictionary dictionaryWithDictionary:dic]; // Rename key if needed if (mutableDic[@"date"]) { mutableDic[@"timestamp"] = mutableDic[@"date"]; } return mutableDic; } // Called after JSON->Model - custom transformation and validation - (BOOL)modelCustomTransformFromDictionary:(NSDictionary *)dic { NSNumber *ts = dic[@"timestamp"]; if (![ts isKindOfClass:[NSNumber class]] || ts.unsignedLongLongValue == 0) { return NO; // Reject model if timestamp is invalid } // Convert Unix timestamp (milliseconds) to NSDate _timestamp = [NSDate dateWithTimeIntervalSince1970:ts.unsignedLongLongValue / 1000.0]; return YES; } // Called after Model->JSON - custom transformation - (BOOL)modelCustomTransformToDictionary:(NSMutableDictionary *)dic { if (!_timestamp) { return NO; // Reject if no timestamp } // Convert NSDate back to Unix timestamp (milliseconds) dic[@"timestamp"] = @((uint64_t)(_timestamp.timeIntervalSince1970 * 1000)); return YES; } @end // Usage NSString *json = @"{\"eventId\":123,\"content\":\"Hello\",\"timestamp\":1401234567000}"; Event *event = [Event yy_modelWithJSON:json]; // event.timestamp = NSDate converted from milliseconds // Invalid data returns nil Event *invalid = [Event yy_modelWithJSON:@"{\"eventId\":123,\"content\":\"Hello\"}"]; // invalid == nil (rejected due to missing timestamp)" ``` -------------------------------- ### Convert NSDictionary to Model Instance Source: https://context7.com/ibireme/yymodel/llms.txt Use `yy_modelWithDictionary:` to create a model instance from an NSDictionary. This method is suitable when you already have data in dictionary format. ```objc // Convert from NSDictionary NSDictionary *dict = @{@"uid": @123456, @"name": @"Harry"}; User *user2 = [User yy_modelWithDictionary:dict]; ``` -------------------------------- ### Convert Model to NSDictionary Source: https://context7.com/ibireme/yymodel/llms.txt Use `yy_modelToJSONObject` to convert a model instance into an NSDictionary. Invalid properties are automatically ignored. ```objc @interface Book : NSObject @property NSString *name; @property NSUInteger pages; @property NSDate *publishDate; @end @implementation Book @end // Create and populate model Book *book = [Book new]; book.name = @"Harry Potter"; book.pages = 256; book.publishDate = [NSDate date]; // Convert to NSDictionary NSDictionary *jsonObject = [book yy_modelToJSONObject]; // {"name":"Harry Potter","pages":256,"publishDate":"2024-01-15T10:30:00+0000"} ``` -------------------------------- ### Custom Property Mapping Source: https://github.com/ibireme/yymodel/blob/master/README.md Map JSON keys (or key paths) to model properties when they differ. Use an array of keys to support multiple JSON keys for a single property. ```objc // JSON: { "n":"Harry Pottery", "p": 256, "ext" : { "desc" : "A book written by J.K.Rowing." }, "ID" : 100010 } // Model: @interface Book : NSObject @property NSString *name; @property NSInteger page; @property NSString *desc; @property NSString *bookID; @end @implementation Book + (NSDictionary *)modelCustomPropertyMapper { return @{@"name" : @"n", @"page" : @"p", @"desc" : @"ext.desc", @"bookID" : @["id",@"ID",@"book_id"]}; } @end ``` -------------------------------- ### Nested Model Conversion Source: https://github.com/ibireme/yymodel/blob/master/README.md YYModel automatically handles nested models. Define the nested model as a property in the parent model class. ```objc // JSON { "author":{ "name":"J.K.Rowling", "birthday":"1965-07-31T00:00:00+0000" }, "name":"Harry Potter", "pages":256 } // Model: (no need to do anything) @interface Author : NSObject @property NSString *name; @property NSDate *birthday; @end @implementation Author @end @interface Book : NSObject @property NSString *name; @property NSUInteger pages; @property Author *author; @end @implementation Book @end ``` -------------------------------- ### Perform Class Introspection with YYClassInfo Source: https://context7.com/ibireme/yymodel/llms.txt Access cached, thread-safe metadata for properties, methods, and ivars of a class using YYClassInfo. ```objc #import "YYClassInfo.h" @interface MyModel : NSObject @property NSString *name; @property NSInteger count; - (void)doSomething; @end @implementation MyModel - (void)doSomething {} @end // Get class info (cached and thread-safe) YYClassInfo *classInfo = [YYClassInfo classInfoWithClass:[MyModel class]]; // Inspect properties for (NSString *propertyName in classInfo.propertyInfos) { YYClassPropertyInfo *propInfo = classInfo.propertyInfos[propertyName]; NSLog(@"Property: %@, Type: %@, Getter: %@", propInfo.name, propInfo.typeEncoding, NSStringFromSelector(propInfo.getter)); } // Inspect methods for (NSString *methodName in classInfo.methodInfos) { YYClassMethodInfo *methodInfo = classInfo.methodInfos[methodName]; NSLog(@"Method: %@, Return type: %@", methodInfo.name, methodInfo.returnTypeEncoding); } // Inspect ivars for (NSString *ivarName in classInfo.ivarInfos) { YYClassIvarInfo *ivarInfo = classInfo.ivarInfos[ivarName]; NSLog(@"Ivar: %@, Offset: %td", ivarInfo.name, ivarInfo.offset); } // Check if class info needs refresh after runtime modification if ([classInfo needUpdate]) { classInfo = [YYClassInfo classInfoWithClass:[MyModel class]]; } ``` -------------------------------- ### Convert Model to NSData Source: https://context7.com/ibireme/yymodel/llms.txt Use `yy_modelToJSONData` to convert a model instance into an NSData object, typically for network transmission or storage. ```objc // Convert to NSData NSData *jsonData = [book yy_modelToJSONData]; ``` -------------------------------- ### Container Property Generic Classes Source: https://context7.com/ibireme/yymodel/llms.txt Specifies element types for collections like NSArray, NSSet, or NSDictionary to enable automatic conversion. ```objc @interface Shadow : NSObject @property NSString *color; @property CGFloat radius; @end @implementation Shadow @end @interface Border : NSObject @property NSString *style; @property CGFloat width; @end @implementation Border @end @interface LayerAttributes : NSObject @property NSString *name; @property NSArray *shadows; // Array @property NSSet *borders; // Set @property NSMutableDictionary *styles; // Dict @end @implementation LayerAttributes + (NSDictionary *)modelContainerPropertyGenericClass { return @{ @"shadows" : [Shadow class], // Using class object @"borders" : Border.class, // Using .class syntax @"styles" : @"Shadow" // Using class name string }; } @end // JSON with arrays and dictionaries NSString *json = @"{\"name\":\"Layer1\",\"shadows\":[{\"color\":\"black\",\"radius\":5},{\"color\":\"gray\",\"radius\":3}],\"borders\":[{\"style\":\"solid\",\"width\":1}]}"; LayerAttributes *attrs = [LayerAttributes yy_modelWithJSON:json]; // attrs.shadows[0] is Shadow instance with color="black", radius=5 // attrs.borders contains Border instances ``` -------------------------------- ### Nested Model Conversion Source: https://context7.com/ibireme/yymodel/llms.txt Automatically maps nested JSON objects to model properties by defining them as model classes. ```objc @interface Author : NSObject @property NSString *name; @property NSDate *birthday; @end @implementation Author @end @interface Book : NSObject @property NSString *name; @property NSUInteger pages; @property Author *author; // Nested model @end @implementation Book @end // JSON with nested object NSString *json = @"{\"name\":\"Harry Potter\",\"pages\":256,\"author\":{\"name\":\"J.K.Rowling\",\"birthday\":\"1965-07-31T00:00:00+0000\"}}"; Book *book = [Book yy_modelWithJSON:json]; // book.name = @"Harry Potter" // book.pages = 256 // book.author.name = @"J.K.Rowling" // book.author.birthday = NSDate for 1965-07-31 // Convert back to JSON preserves nested structure NSDictionary *jsonObject = [book yy_modelToJSONObject]; // {"name":"Harry Potter","pages":256,"author":{"name":"J.K.Rowling","birthday":"1965-07-31T00:00:00+0000"}} ``` -------------------------------- ### Convert NSData to Model Instance Source: https://context7.com/ibireme/yymodel/llms.txt Use `yy_modelWithJSON:` with an NSData object to convert JSON data into a model instance. Ensure the NSData contains valid JSON. ```objc // Convert from NSData NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; User *user3 = [User yy_modelWithJSON:jsonData]; ``` -------------------------------- ### Convert JSON String to Model Instance Source: https://context7.com/ibireme/yymodel/llms.txt Use `yy_modelWithJSON:` to create a model instance from a JSON string. Supports automatic type conversion for dates, URLs, numbers, and booleans. ```objc // Define your model class @interface User : NSObject @property UInt64 uid; @property NSString *name; @property NSDate *created; @end @implementation User @end // Convert from JSON string NSString *jsonString = @"{\"uid\":123456,\"name\":\"Harry\",\"created\":\"1965-07-31T00:00:00+0000\"}"; User *user = [User yy_modelWithJSON:jsonString]; // user.uid = 123456 // user.name = @"Harry" // user.created = NSDate for 1965-07-31 ``` -------------------------------- ### Array Model Conversion Source: https://context7.com/ibireme/yymodel/llms.txt Converts JSON arrays or dictionaries directly into collections of model objects. ```objc @interface User : NSObject @property NSString *name; @property NSUInteger age; @end @implementation User @end // JSON array NSString *json = @"[{\"name\":\"Mary\",\"age\":25},{\"name\":\"Joe\",\"age\":30},{\"name\":\"Bob\",\"age\":28}]"; // Convert to array of User objects NSArray *users = [NSArray yy_modelArrayWithClass:[User class] json:json]; // users[0].name = @"Mary", users[0].age = 25 // users[1].name = @"Joe", users[1].age = 30 // users[2].name = @"Bob", users[2].age = 28 // Also works with NSDictionary or NSData input NSDictionary *userDict = @{@"user1": @{@"name": @"Alice"}, @"user2": @{@"name": @"Eve"}}; NSDictionary *userMap = [NSDictionary yy_modelDictionaryWithClass:[User class] json:userDict]; // userMap[@"user1"].name = @"Alice" ``` -------------------------------- ### Update Model from JSON String Source: https://context7.com/ibireme/yymodel/llms.txt Use `yy_modelSetWithJSON:` to update an existing model instance with values from a JSON string. This is efficient for partial updates. ```objc @interface Profile : NSObject @property NSString *name; @property NSString *email; @property NSUInteger age; @end @implementation Profile @end // Create initial model Profile *profile = [Profile new]; profile.name = @"John"; profile.email = @"john@example.com"; profile.age = 25; // Update with partial JSON data BOOL success = [profile yy_modelSetWithJSON:@"{\"name\":\"Jane\",\"age\":30}"]; // profile.name = @"Jane" (updated) // profile.email = @"john@example.com" (unchanged) // profile.age = 30 (updated) ``` -------------------------------- ### Update Model from Dictionary Source: https://context7.com/ibireme/yymodel/llms.txt Use `yy_modelSetWithDictionary:` to update an existing model instance with values from an NSDictionary. This method allows for flexible updates to model properties. ```objc // Update with dictionary [profile yy_modelSetWithDictionary:@{@"email": @"jane@example.com"}]; ``` -------------------------------- ### Convert Model to JSON String Source: https://context7.com/ibireme/yymodel/llms.txt Use `yy_modelToJSONString` to serialize a model instance into a JSON string. This is useful for sending data over networks or saving to files. ```objc // Convert to JSON string NSString *jsonString = [book yy_modelToJSONString]; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.