核心数据: - 如何更新阵列中的值(可转换)

时间:2015-07-31 05:12:03

标签: iphone core-data xcode6.1

我在使用核心数据的应用程序上工作,以便在本地设备中保存数据。在Core数据中,我使用Transformable格式将数据保存在数组中,但是,我不知道如何更新数组中的特定值。 我的更新数据代码在这里

package com.example.namrathasrinivas.karnatakatemples;

import android.app.ListActivity;
import android.graphics.BitmapFactory;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Intent;

/**
 * Created by namrathasrinivas on 23/07/15.
 */
public class page4 extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page4);

        int[] drawables = {R.drawable.img1,R.drawable.img2,R.drawable.img3,R.drawable.img4,R.drawable.img5,R.drawable.img6};

        LinearLayout layout = (LinearLayout) findViewById(R.id.linear);
        for (int i = 0; i < 6; i++) {
            ImageView imageView = new ImageView(this);
            imageView.setId(i);
            imageView.setPadding(5, 5, 5, 5);
            imageView.setImageBitmap(BitmapFactory.decodeResource(
                    getResources(), drawables[i]));

            imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
            layout.addView(imageView);
        }
    } 
}

以下是核心数据中的保存数组:

 NSManagedObjectContext *context = [self managedObjectContext];
   NSManagedObject *user = [NSEntityDescription    insertNewObjectForEntityForName:@"Type" inManagedObjectContext:context];
 NSError *error = nil;
 //Set up to get the thing you want to update
 NSFetchRequest * request = [[NSFetchRequest alloc] init];
   NSEntityDescription *entity = [NSEntityDescription entityForName:@"Type"inManagedObjectContext:context];
 [request setEntity:entity];
 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"businessTypes == %@", @"Others"];
 [request setPredicate:predicate];

   AppDelegate *app = (AppDelegate*)[[UIApplication sharedApplication]delegate];
  NSArray *results = [self.managedObjectContext executeFetchRequest:request error:&error];

if (results == nil) {
    // This implies an error has occurred.
    NSLog(@"Error from Core Data: %@", error);
} else {
    if (results.count == 0) {
        // No objects saved, create a new one...
    } else {
        // At least one object saved.  There should be only one
        // so use the first...
        user = [results lastObject];
        [user setValue:@"Management" forKey:@"businessTypes"];
    }
}

if (![self.managedObjectContext save:&error]) {
   //Handle any error with the saving of the context
}
else{
  [app saveContext];
   NSLog(@"update value successfully");
}

所以我想在阵列中将“其他”更新为“管理”。

当我运行此代码时,我没有错误,但我没有更新索引数组的特定值。 谢谢你的帮助。

2 个答案:

答案 0 :(得分:1)

Perhaps you are confusing your entities. You fetch an entity called Type but you are calling the object user, indicating that perhaps you wanted to fetch a user that has a certain business type.

If each user has only one "business type", you do not need a Type entity, just a string attribute for the User entity.

If each user can have more than one business type, you should have an entity Type with a name attribute that includes one term indicating the business type, and it should be modeled as a many-to-many relationship.

User <<--------->>  Type

To set all types that are now called "Other" to "Management", you would fetch the Type with name "Other", change it and save. To only change one of a user's business types from "Other" to "Management", you would: fetch the user, remove the "Other" type, fetch the "Management" type, add it to the user and save.

If your businessTypes attribute is supposed to be a transformable array with hard-coded strings, you should probably change the data model as described above. You will have much more flexibility and power for searching and handling the data with a clean Core Data model.

答案 1 :(得分:-1)

您必须像这段代码一样修改更新功能,然后您将获得所需的输出

NSManagedObjectContext *context = [self managedObjectContext];
NSError *error = nil;
NSFetchRequest * request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Type"inManagedObjectContext:context];
[request setEntity:entity];
 request.propertiesToFetch= @[ @"businessTypes"];
AppDelegate *app = (AppDelegate*)[[UIApplication sharedApplication]delegate];
NSArray *results = [self.managedObjectContext executeFetchRequest:request error:&error];

if (results == nil) {
    // This implies an error has occurred.
    NSLog(@"Error from Core Data: %@", error);
} else {
    if (results.count == 0) {
        // No objects saved, create a new one...
    } else {


        int loopCount = (int)results.count;
        Type* entityType = nil;
        for (int index=0; index<loopCount; index++) {
            entityType = (Type*)results[index];
            if (entityType.businessTypes!=nil) {
                NSUInteger reqIndex = [entityType.businessTypes indexOfObject:@"Others"];
                [entityType.businessTypes replaceObjectAtIndex:reqIndex withObject:@"Management"];
                [entityType setValue:entityType.businessTypes forKey:@"businessTypes"];
            }

        }
}
if (![self.managedObjectContext save:&error]) {
    //Handle any error with the saving of the context
}
else{
    [app saveContext];
    NSLog(@"update value successfully");
}