seguedestination seguedestination - 6 months ago 10
iOS Question

Is there a way to copy NSObject's properties?

I want to implement a method that can copy object's property from A to B.For example


A's name = @"a",

A's code = @"1",

A's address = 0x100(fake).


And after I use


B's name = @"b",

B's code = @"2",

B's address = 0x200.


After I use the custom copy method,


A = [A copyWith:B];


Now


A's name = @"b",

A's code = @"2",


but


A's address = 0x100


does not change.

Code:

#import <Foundation/Foundation.h>
@interface MyObject : NSObject
@property (copy, nonatomic) NSString *name;
@property (copy, nonatomic) NSString *code;
@end


Any ideas?

Answer

Use objc/runtime. Fetch all the objc_propertis from the new object and use KVC to set the value for the old object

Comments