0Pricing
Objective-C iOS Development for Legacy & Enterprise Apps · درس

قوائم الخصائص والأرشفة

تعلّموا حفظ هياكل البيانات البسيطة وتحميلها باستخدام NSUserDefaults وقوائم الخصائص وNSKeyedArchiver.

قوائم الخصائص والأرشفة درس مجاني في Objective-C iOS Development for Legacy & Enterprise Apps على CoddyKit. هذا هو الدرس 1 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Objective-C iOS Development for Legacy & Enterprise Apps، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Objective-C iOS Development for Legacy & Enterprise Apps 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

Why Data Persistence?

When your app closes, all its in-memory data disappears. To keep user settings, game progress, or other important information, you need data persistence.

Data persistence means saving data to a permanent storage location, like a file on the device, so it can be retrieved later.

Understanding Property Lists

Property Lists (PLists) are a standard way for iOS apps to store structured data. They're XML or binary files that represent common data types.

  • Supported Types: NSString, NSNumber, NSDate, NSData, NSArray, NSDictionary.
  • PLists are great for small, hierarchical data like user preferences or configuration settings.

NSUserDefaults for Simple Data

NSUserDefaults is a convenient way to store small amounts of data, typically user preferences or application settings.

It works like a dictionary, saving key-value pairs directly to a Property List file managed by the system. It's ideal for simple data types.

Saving with NSUserDefaults

To save data using NSUserDefaults, you get the standard user defaults object and then use methods like setObject:forKey: or setInteger:forKey:.

The synchronize method (though often not strictly necessary in modern iOS) ensures data is written to disk immediately.

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        
        // Save a string
        [defaults setObject:@"CoddyKit User" forKey:@"username"];
        
        // Save an integer
        [defaults setInteger:123 forKey:@"userScore"];
        
        // Optional: Ensure data is written immediately
        [defaults synchronize];
        
        NSLog(@"Data saved to NSUserDefaults!");
    }
    return 0;
}

Loading with NSUserDefaults

Retrieving data is just as easy! Use methods like stringForKey: or integerForKey: with the same keys you used for saving.

Remember that if a key doesn't exist, you'll get nil for objects or a default value (like 0 for integers).

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        
        // Load a string
        NSString *username = [defaults stringForKey:@"username"];
        
        // Load an integer
        NSInteger userScore = [defaults integerForKey:@"userScore"];
        
        NSLog(@"Loaded Username: %@", username ? username : @"(Not set)");
        NSLog(@"Loaded User Score: %ld", (long)userScore);
    }
    return 0;
}

Beyond NSUserDefaults

While NSUserDefaults is great for simple data, it has limitations:

  • Not suitable for large amounts of data.
  • Only handles Property List compatible types.
  • Doesn't easily store custom objects (unless converted to NSData).

For more complex data, especially custom objects, we need a different approach: Archiving.

Archiving Custom Objects

Archiving allows you to convert complex object graphs (like instances of your custom classes) into a flattened, binary representation (NSData).

This NSData can then be saved to a file or even stored in NSUserDefaults. The key player here is the NSCoding protocol and NSKeyedArchiver.

Implementing NSCoding Protocol

To make your custom Objective-C objects archivable, they must conform to the NSCoding protocol.

This involves implementing two methods: encodeWithCoder: (to save properties) and initWithCoder: (to load properties).

#import <Foundation/Foundation.h>

@interface GameScore : NSObject <NSCoding>
@property (nonatomic, strong) NSString *playerName;
@property (nonatomic) NSInteger score;
@end

@implementation GameScore

- (instancetype)initWithPlayerName:(NSString *)name score:(NSInteger)value {
    self = [super init];
    if (self) {
        _playerName = name;
        _score = value;
    }
    return self;
}

// Save properties to the coder
- (void)encodeWithCoder:(NSCoder *)coder {
    [coder encodeObject:self.playerName forKey:@"playerName"];
    [coder encodeInteger:self.score forKey:@"score"];
}

// Load properties from the coder
- (instancetype)initWithCoder:(NSCoder *)coder {
    self = [super init];
    if (self) {
        _playerName = [coder decodeObjectForKey:@"playerName"];
        _score = [coder decodeIntegerForKey:@"score"];
    }
    return self;
}

- (NSString *)description {
    return [NSString stringWithFormat:@"Player: %@, Score: %ld", self.playerName, (long)self.score];
}

@end

Archiving with NSKeyedArchiver

Once your custom class conforms to NSCoding, you can use NSKeyedArchiver to convert an object into NSData.

This example shows how to create a GameScore object and archive it. The resulting NSData can then be written to a file.

#import <Foundation/Foundation.h>

// GameScore class (from previous scene)
@interface GameScore : NSObject <NSCoding>
@property (nonatomic, strong) NSString *playerName;
@property (nonatomic) NSInteger score;
@end
@implementation GameScore
- (instancetype)initWithPlayerName:(NSString *)name score:(NSInteger)value { self = [super init]; if (self) { _playerName = name; _score = value; } return self; }
- (void)encodeWithCoder:(NSCoder *)coder { [coder encodeObject:self.playerName forKey:@"playerName"]; [coder encodeInteger:self.score forKey:@"score"]; }
- (instancetype)initWithCoder:(NSCoder *)coder { self = [super init]; if (self) { _playerName = [coder decodeObjectForKey:@"playerName"]; _score = [coder decodeIntegerForKey:@"score"]; } return self; }
- (NSString *)description { return [NSString stringWithFormat:@"Player: %@, Score: %ld", self.playerName, (long)self.score]; }
@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        GameScore *playerData = [[GameScore alloc] initWithPlayerName:@"Hero" score:1000];
        
        NSError *error = nil;
        NSData *archivedData = [NSKeyedArchiver archivedDataWithRootObject:playerData
                                                      requiringSecureCoding:NO
                                                                      error:&error];
        
        if (archivedData && !error) {
            NSLog(@"GameScore object archived successfully! Data length: %lu bytes", (unsigned long)archivedData.length);
            // In a real app, you'd save archivedData to a file, e.g.,
            // [archivedData writeToFile:@"/tmp/game_score.data" atomically:YES];
        } else {
            NSLog(@"Archiving failed: %@", error);
        }
    }
    return 0;
}

Unarchiving with NSKeyedUnarchiver

To get your object back, you use NSKeyedUnarchiver to convert the NSData back into an object.

This process calls the initWithCoder: method of your NSCoding-conforming class, reconstructing the object.

#import <Foundation/Foundation.h>

// GameScore class (from previous scene)
@interface GameScore : NSObject <NSCoding>
@property (nonatomic, strong) NSString *playerName;
@property (nonatomic) NSInteger score;
@end
@implementation GameScore
- (instancetype)initWithPlayerName:(NSString *)name score:(NSInteger)value { self = [super init]; if (self) { _playerName = name; _score = value; } return self; }
- (void)encodeWithCoder:(NSCoder *)coder { [coder encodeObject:self.playerName forKey:@"playerName"]; [coder encodeInteger:self.score forKey:@"score"]; }
- (instancetype)initWithCoder:(NSCoder *)coder { self = [super init]; if (self) { _playerName = [coder decodeObjectForKey:@"playerName"]; _score = [coder decodeIntegerForKey:@"score"]; } return self; }
- (NSString *)description { return [NSString stringWithFormat:@"Player: %@, Score: %ld", self.playerName, (long)self.score]; }
@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // Simulate archived data (in a real app, you'd load from a file)
        GameScore *originalPlayerData = [[GameScore alloc] initWithPlayerName:@"Hero" score:1000];
        NSData *archivedData = [NSKeyedArchiver archivedDataWithRootObject:originalPlayerData requiringSecureCoding:NO error:nil];
        
        if (archivedData) {
            NSError *error = nil;
            GameScore *loadedPlayerData = [NSKeyedUnarchiver unarchivedObjectOfClass:[GameScore class]
                                                                             fromData:archivedData
                                                                                error:&error];
            
            if (loadedPlayerData && !error) {
                NSLog(@"Unarchived Player Data: %@", loadedPlayerData);
                NSLog(@"Player Name: %@", loadedPlayerData.playerName);
                NSLog(@"Score: %ld", (long)loadedPlayerData.score);
            } else {
                NSLog(@"Unarchiving failed: %@", error);
            }
        } else {
            NSLog(@"Archiving failed, cannot unarchive.");
        }
    }
    return 0;
}

Quick Check: Data Storage

Which of the following is BEST suited for storing a user's 'dark mode' preference (a simple boolean value) in an Objective-C iOS app?

Recap & Next Steps

Great job! You've learned the fundamentals of data persistence in Objective-C:

  • Property Lists (PLists): XML/binary files for structured data.
  • NSUserDefaults: Ideal for small user preferences and settings using key-value pairs.
  • NSCoding & NSKeyedArchiver: For converting custom objects into NSData for storage and retrieval.

These methods are crucial for making your apps remember information between sessions. Next, we'll explore Core Data for more robust object graph management!

الأسئلة الشائعة

هل درس «قوائم الخصائص والأرشفة» مجاني؟

نعم — نص درس «قوائم الخصائص والأرشفة» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Objective-C iOS Development for Legacy & Enterprise Apps، انتقل إلى CoddyKit PRO. تتضمن دورة Objective-C iOS Development for Legacy & Enterprise Apps 4 دروس في المجموع.

ماذا ستتعلم في «قوائم الخصائص والأرشفة»؟

تعلّموا حفظ هياكل البيانات البسيطة وتحميلها باستخدام NSUserDefaults وقوائم الخصائص وNSKeyedArchiver. تتمرن على Objective-C iOS Development for Legacy & Enterprise Apps مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Objective-C iOS Development for Legacy & Enterprise Apps؟

لا تُشترط خبرة سابقة. Objective-C iOS Development for Legacy & Enterprise Apps على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 1 من أصل 4.

كم من الوقت يستغرق درس «قوائم الخصائص والأرشفة»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Objective-C iOS Development for Legacy & Enterprise Apps هذا؟

نعم. كل درس في Objective-C iOS Development for Legacy & Enterprise Apps يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. قوائم الخصائص والأرشفة
  2. أساسيات Core Data
  3. دمج SQLite باستخدام FMDB
  4. تخزين التفضيلات باستخدام NSUserDefaults
← العودة إلى Objective-C iOS Development for Legacy & Enterprise Apps