如何从NSUserDefaults检索数据?

时间:2015-06-01 04:51:11

标签: ios swift audio nsuserdefaults mpmediaitemcollection

目前,我尝试制作音乐播放列表应用程序。我尝试从NSUserDefaults保存和检索播放列表数据。保存数据时没有问题,但检索数据时出错。

我得到了:

  

由于未捕获的异常'MPMediaItemCollectionInitException'而终止应用程序,原因:' - 不支持-init,请使用-initWithItems:

我正在关注Play iPod playlist retrieved from a saved persistentid list的答案,但我尝试用swift编写。

这是我的保存功能:

func savePlaylist(var mediaItemCollection: MPMediaItemCollection){

    var items: NSArray = mediaItemCollection.items

    var listToSave: NSMutableArray = NSMutableArray()

    for song in items{

        var persistentId: AnyObject! = song.valueForProperty(MPMediaItemPropertyPersistentID)

        listToSave.addObject(persistentId)

    }

    var data: NSData = NSKeyedArchiver.archivedDataWithRootObject(listToSave)

    NSUserDefaults.standardUserDefaults().setObject(data, forKey: "songsList")
    NSUserDefaults.standardUserDefaults().synchronize()

}

这是我的检索功能:

func setupMusic(){

    if NSUserDefaults.standardUserDefaults().objectForKey("songsList") != nil{

        var theList: NSMutableArray = NSMutableArray()

        var data: NSData = (NSUserDefaults.standardUserDefaults().objectForKey("songsList") as? NSData)!

        var decodedData: NSArray  = (NSKeyedUnarchiver.unarchiveObjectWithData(data) as? NSArray)!

        theList.addObjectsFromArray(decodedData as [AnyObject])

        var allTheSongs: NSMutableArray = NSMutableArray()

        for var i = 0; i < theList.count; i++ {

            var songQuery = MPMediaQuery.songsQuery()

            var songs: NSArray = songQuery.items

            allTheSongs.addObject(songs)

        }

        var currentQueue: MPMediaItemCollection = MPMediaItemCollection()

        myMusicPlayer?.setQueueWithItemCollection(currentQueue)


    }else{
        println("fail!!!!!!!!!!!!")
    }

}

我该如何解决?

2 个答案:

答案 0 :(得分:1)

以下是问题var currentQueue: MPMediaItemCollection = MPMediaItemCollection()

您必须init使用商品

根据苹果的documentation

  

初​​始化(项:)   指定初始化程序

     

使用一系列媒体项初始化媒体项集合。   声明

     

夫特

     

init!(项目项目:[AnyObject]!)   参数   项目

     

您要分配给媒体项目集合的项目数组。

您必须使用

等项目进行初始化
var currentQueue: MPMediaItemCollection = MPMediaItemCollection(items:itemsArray)

答案 1 :(得分:0)

我给你一个非常简单的方法来处理任何类型的对象并从NSUserDefault中检索。 您无需显式使用归档和取消归档。 只需创建一个NSUserDefaults类别,如下所示

#import <Foundation/Foundation.h>
@interface NSUserDefaults (AKSNSUserDefaults)
- (void)saveCustomObject:(id<NSCoding>)object
                     key:(NSString *)key;
- (id<NSCoding>)loadCustomObjectWithKey:(NSString *)key;
@end  

@implementation NSUserDefaults (AKSNSUserDefaults)

- (void)saveCustomObject:(id<NSCoding>)object
                     key:(NSString *)key {
    NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
    [self setObject:encodedObject forKey:key];
    [self synchronize];

}

- (id)loadCustomObjectWithKey:(NSString *)key {
    NSData *encodedObject = [self objectForKey:key];
    id object = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
    return object;
}

@end

并且您的NSUserDefaults已准备好存储任何对象。但有一点需要在对象模型中使用NSCoder

例如:

#import <Foundation/Foundation.h>

@interface AKSClassA : NSObject<NSCoding>
// declared some property 
@property (nonatomic,assign) NSInteger userID;
@property (nonatomic,strong) NSString *userName;
@end
#import "AKSClassA.h"
@implementation AKSClassA
@synthesize userID;
@synthesize userName;
-(id)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super init]) {

        self. userID = [aDecoder decodeIntegerForKey:@"userID"];
        self. userName = [aDecoder decodeObjectForKey:@"userName"];

   }
    return self;
}
-(void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeInteger:userID  forKey:@"userID"];
    [aCoder encodeObject:userName forKey:@"userName"];
}
@end
// in some class if you are using classA object member to store and retrieve with value  example below 
// to save data in NSUserDefaults 
  AKSClassA *obj =[array1 objectAtIndex:index];
  [[NSUserDefaults standardUserDefaults] saveCustomObject:button key:@"userData"];

// to retrieve data 
 AKSClassA *obj1 = (AKSClassA*)[[NSUserDefaults standardUserDefaults]loadCustomObjectWithKey:@"userData"];

    [titleLabel  setText:obj1.userName];