iOS Core Data: 存储自定义对象 Save Custom NSObject

思路:将NSObject转化为NSData,然后将NSData存入到Core Data中

Core Data实现

添加数据:

    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *context = [appDelegate managedObjectContext];
    NSManagedObject *newContact;
    newContact = [NSEntityDescription insertNewObjectForEntityForName:@"Contact" inManagedObjectContext:context];
    
    Person *person = [[Person alloc] init];
    person.name = @"Xiaoming";
    person.number = @"1008610086";
    
    Birthday *birthday = [[Birthday alloc] init];
    birthday.year = @"2000";
    birthday.month = @"January";
    birthday.day = @"1st";
    person.birthday = birthday;

    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:person];
    [newContact setValue:data forKey:@"person"];
    
    NSError *error;
    [context save:&error];
获取数据:
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];

    NSManagedObjectContext *context = [appDelegate managedObjectContext];
    NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Contact" inManagedObjectContext:context];
    [request setEntity:entityDesc];
    
    NSManagedObject *matches = nil;
    
    NSError *error;
    NSArray *objects = [context executeFetchRequest:request
                                              error:&error];
    
    if ([objects count] == 0)
    {
        NSLog(@"No matches");
    }
    else
    {
        for (int i = 0; i < [objects count]; i++)
        {
            matches = objects[i];
            NSData *data = [matches valueForKey:@"person"];
            Person *person = [NSKeyedUnarchiver unarchiveObjectWithData:data];
            NSLog(@"My name is %@. I was born on %@ %@, %@. My phone number is %@", person.name, person.birthday.month, person.birthday.day, person.birthday.year, person.number);
        }
    }
Model文件中设置person的类型设为Binary Data:


Person和Birthday这两个自定的NSObject,都需要使用NSCoding,实现initWithCoder和encodeWithCoder两个方法

Person

//
//  Person.h
//  CoreDataTest
//

#import <Foundation/Foundation.h>
#import "Birthday.h"

@interface Person : NSObject<NSCoding>

@property (strong, nonatomic) NSString *name;
@property (strong, nonatomic) NSString *number;
@property (strong, nonatomic) Birthday *birthday;

- (id)init;

@end
//
//  Person.m
//  CoreDataTest
//

#import "Person.h"

@implementation Person

- (id)init{
    self.name  = nil;
    self.number  = nil;
    
    return self;
}

- (id)initWithCoder:(NSCoder *)decoder{
    if (self = [super init]){
        self.name  = [decoder decodeObjectForKey: @"name"];
        self.number  = [decoder decodeObjectForKey: @"number"];
        self.birthday = [decoder decodeObjectForKey: @"birthday"];
    }
    
    return self;
}

- (void)encodeWithCoder:(NSCoder *)encoder{
    [encoder encodeObject:self.name forKey:@"name"];
    [encoder encodeObject:self.number forKey:@"number"];
    [encoder encodeObject:self.birthday forKey:@"birthday"];
}

@end
Birthday
//
//  Birthday.h
//  CoreDataTest
//

#import <Foundation/Foundation.h>

@interface Birthday : NSObject<NSCoding>

@property (strong, nonatomic) NSString *year;
@property (strong, nonatomic) NSString *month;
@property (strong, nonatomic) NSString *day;

- (id)init;

@end
//
//  Birthday.m
//  CoreDataTest
//

#import "Birthday.h"

@implementation Birthday

- (id)init{
    self.year  = nil;
    self.month  = nil;
    self.day  = nil;

    return self;
}

- (id)initWithCoder:(NSCoder *)decoder{
    if (self = [super init]){
        self.year  = [decoder decodeObjectForKey: @"year"];
        self.month  = [decoder decodeObjectForKey: @"month"];
        self.day = [decoder decodeObjectForKey: @"day"];
    }
    
    return self;
}

- (void)encodeWithCoder:(NSCoder *)encoder{
    [encoder encodeObject:self.year forKey:@"year"];
    [encoder encodeObject:self.month forKey:@"month"];
    [encoder encodeObject:self.day forKey:@"day"];
}

@end


参考链接:

http://sam.roon.io/archiving-objective-c-objects-with-nscoding

https://coderwall.com/p/mx_wmq/how-to-save-a-nsarray-nsmutablearray-in-core-data

http://pinkstone.co.uk/how-to-save-a-uiimage-in-core-data-and-retrieve-it/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
iOS 上,你可以使用 AVAudioRecorder 和 AVAudioPlayer 来同时进行录音和播放。 首先,你需要创建一个 AVAudioRecorder 实例来录制音频。然后,你可以在录制音频的同时,创建一个 AVAudioPlayer 实例来播放音频。在录制和播放过程中,你需要将音频数据写入文件和缓存中。 以下是一个示例代码,展示了如何同时录制和播放音频: ```swift import AVFoundation class AudioController: NSObject, AVAudioRecorderDelegate { var recorder: AVAudioRecorder? var player: AVAudioPlayer? func startRecordingAndPlayback() { // 设置录音会话 let session = AVAudioSession.sharedInstance() try? session.setCategory(AVAudioSession.Category.playAndRecord, mode: .default, options: []) try? session.setActive(true) // 设置录音器 let settings: [String: Any] = [AVFormatIDKey: Int(kAudioFormatMPEG4AAC), AVSampleRateKey: 44100.0, AVNumberOfChannelsKey: 2, AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue] let url = URL(fileURLWithPath: NSTemporaryDirectory() + "recording.m4a") recorder = try? AVAudioRecorder(url: url, settings: settings) recorder?.delegate = self recorder?.prepareToRecord() recorder?.record() // 设置播放器 let audioData = try? Data(contentsOf: url) player = try? AVAudioPlayer(data: audioData ?? Data()) player?.prepareToPlay() player?.play() } // AVAudioRecorderDelegate 方法 func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) { player?.stop() } } ``` 在这个示例中,我们首先设置了一个音频会话,然后创建了一个 AVAudioRecorder 实例来录制音频。同时,我们也创建了一个 AVAudioPlayer 实例来播放音频。最后,在录音完成后,我们停止了播放器。 你可以根据自己的需求进行更改和调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值