使用一个核心数据属性填充数组

时间:2014-12-08 05:20:25

标签: arrays swift core-data

将输入从一个属性放入数组时遇到了一些麻烦。然后,此数组将用于UIPickerview。语言是斯威夫特。

有很多关于swift中的Pickerviews和swift中的Core Data的教程。但我还没有找到解释如何用一个属性填充数组的方法。

更糟糕的是,我仍然很难将目标c转换成swift。

所以我有两个问题:

1我的解决方案是否正确从一个属性构建数组然后用该数组中的内容填充Pickerview?

2你如何在swift中获得该数组?

objective c code on core data => array


目标C来自链接:

NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]
                                initWithEntityName:@"WeightLog"];
self.contactarray = [[managedObjectContext executeFetchRequest:fetchRequest
                                                         error:nil] mutableCopy];

titleNames = [[NSMutableArray alloc] init];
for (int i =0; i<=self.contactarray.count; i++) {
    NSManagedObject *device = [self.contactarray objectAtIndex:i];
    [titleNames addObject:device];
}

我不能用Swift编写的部分:

NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]
            initWithEntityName:@"WeightLog"];
        self.contactarray = [[managedObjectContext executeFetchRequest:fetchRequest
        error:nil] mutableCopy];

谢谢!


编辑: 工作代码!

var myTitle: String = ""


var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
        var context:NSManagedObjectContext = appDel.managedObjectContext!

        let fetchRequest = NSFetchRequest(entityName:"MyEntity")
        var myTitles: [String] = []
        if let myLogs = context.executeFetchRequest(fetchRequest, error: nil) {
            myTitles = myLogs.map { $0.myTitle } // get an array of the 'myTitle' attributes
            println(myTitles)

2 个答案:

答案 0 :(得分:2)

我只是在这里输入,所以不确定它是否会编译:

let moc = self.managedObjectContext()
let fetchRequest = NSFetchRequest(entityName:"WeightLog")
var titleNames: [String] = []
if let weightLogs = moc.executeFetchRequest(fetchRequest, error: nil) as? [WeightLog] {
  titleNames = weightLogs.map { $0.title } // get an array of the 'title' attributes
}

如果您从方法中返回titleNames数组,那么我就这样写,即不使用var titleNames

let moc = self.managedObjectContext()
let fetchRequest = NSFetchRequest(entityName:"WeightLog")
if let weightLogs = moc.executeFetchRequest(fetchRequest, error: nil) as? [WeightLog] {
  return weightLogs.map { $0.title } // get an array of the 'title' attributes
} else {
  return []
}

答案 1 :(得分:1)

lazy  var managedObjectContext : NSManagedObjectContext? = {   
    let appDelegate  = UIApplication.sharedApplication().delegate as AppDelegate

    if let managedObjectContext  = appDelegate.managedObjectContext 
    {
        return managedObjectContext
    }
    else 
    {
        return nil
    }
}()

let fetchRequest = NSFetchRequest(entityName: "Entity")

if let fetchResults = managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as? [Entity] 
{

    for info in fetchResults
    {
        println(info.valueForKey("keyname"));
    }
}