Immutable Object in Objective-C: Big init Method?

I want to have an object with immutable fields in Objective-C.

In C #, I would use properties with private installers and a large constructor.

What will I use in Objective-C?

Using @property doesn't seem to allow me to declare the installer as private.

Using

initWithData: (NSString*) something createDate: (NSDate*) date userID: (long) uid

Looks too verbose if I have more than 4 properties set.

Would I declare getters in a .h file and setters in .m only?

I need to use saving or copying to something and a date (by the way: which of these two should I use?), So I need the code in the installer.

Or is there something else like the immutable keyword?

+3
source share
2 answers

read-write, , . , , .

Person:

// Person.h
#import <Foundation/Foundation.h>

@interface Person : NSObject {
@private
    NSString *name_;
    NSDate *dateOfBirth_;
}

@property (readonly, copy) NSString *name;
@property (readonly, copy) NSDate *dateOfBirth;

/*! Initializes a Person with copies of the given name and date of birth. */
- (id)initWithName:(NSString *)name dateOfBirth:(NSDate *)dateOfBirth;

@end

// Person.m
#import "Person.h"

@implementation Person

@synthesize name = name_;
@synthesize dateOfBirth = dateOfBirth_;

- (id)initWithName:(NSString *)name dateOfBirth:(NSDate *)dateOfBirth {
    self = [super init];
    if (self) {
        name_ = [name copy];
        dateOfBirth_ = [dateOfBirth copy];
    }

    return self;
}

- (void)dealloc {
    [name_ release];
    [dateOfBirth_ release];

    [super dealloc];
}

@end

-, , Person.m, name dateOfBirth readwrite. , ; , - .

, , . . ( , Mac OS X iOS, #) , .

, copy, . . -, , MutablePerson. ! , copy , , - name dateOfBirth . , -initWithName:dateOfBirth:, , ; . -, NSString, NSDate ; , , - . ( NSDate, , - ...)

, , . , , - .

. , , -isEqual: -hash , , NSCopying. :

@interface Person (ImmutableValueClass) <NSCopying>
@end

@implementation Person (ImmutableValueClass)

- (NSUInteger)hash {
    return [name_ hash];
}

- (BOOL)isEqual:(id)other {
    Person *otherPerson = other;
    // Using [super isEqual:] to allow easier reparenting
    // -[NSObject isEqual:] is documented as just doing pointer comparison
    return ([super isEqual:otherPerson]
            || ([object isKindOfClass:[self class]]
                && [self.name isEqual:otherPerson.name]
                && [self.dateOfBirth isEqual:otherPerson.dateOfBirth]));
}

- (id)copyWithZone:(NSZone *)zone {
    return [self retain];
}

@end

, , , , , @interface @implementation. , -hash -isEqual:, , NSObject. , , -copyWithZone: , self, , .

Core Data, , ; Core Data , -hash -isEqual:. NSCopying Core Data NSManagedObject; , "" , Core Data, , , .

+12

- @property; readonly copy retain ( , , ). , , @synthesize, setter. , setter, , Objective-C. - , . , , . , , .

+1

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


All Articles