Objective C托管对象使用及Entry实体数据访问、initWithEntityName用法咨询
Hey there! Let's tackle your two Objective-C questions with clear, practical examples—no jargon overload.
Managed objects (specifically NSManagedObject from Core Data) are the backbone of Core Data's data model. Here's a step-by-step guide to using them:
First, set up your data model
Create a.xcdatamodeldfile in Xcode, add an Entity (like yourEntry), and define its attributes (e.g.,cumulativeTime,latitude,entryName). This is where you map your data structure.Generate the managed object subclass
Select yourEntryentity in the data model, go toEditor > Create NSManagedObject Subclass, and let Xcode generateEntry.handEntry.m. This gives you type-safe access to your entity's properties.Get the managed object context
The context is where all Core Data operations happen. For iOS 10+, useNSPersistentContainer(usually set up in yourAppDelegate):AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; NSManagedObjectContext *context = appDelegate.persistentContainer.viewContext;Create and save a new managed object
UseNSEntityDescriptionto insert a new object into the context, set its properties, then save:// Insert a new Entry Entry *newEntry = [NSEntityDescription insertNewObjectForEntityForName:@"Entry" inManagedObjectContext:context]; // Set properties newEntry.cumulativeTime = @"0000"; newEntry.latitude = @"12.972442"; newEntry.entryName = @"Bangalore"; // Save the context NSError *saveError = nil; if (![context save:&saveError]) { NSLog(@"Failed to save entry: %@", saveError.localizedDescription); }Fetch existing managed objects
UseNSFetchRequestto retrieve objects from the store:NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Entry"]; NSError *fetchError = nil; NSArray *entries = [context executeFetchRequest:fetchRequest error:&fetchError]; if (fetchError) { NSLog(@"Fetch failed: %@", fetchError.localizedDescription); } else { // Loop through results for (Entry *entry in entries) { NSLog(@"Entry: %@, Latitude: %@", entry.entryName, entry.latitude); } }
initWithEntityName: Let's break this down into two parts:
Accessing Data from the Entry Array
Your example shows an array of Entry managed objects. Even if you can't "directly access internal data" at first, you have two reliable ways to get the values:
If you have the Entry subclass
Just loop through the array and use dot syntax to access properties—this is the cleanest approach:NSArray *entriesArray = // Your existing array of Entry objects for (Entry *entry in entriesArray) { NSString *name = entry.entryName; NSString *latitude = entry.latitude; NSString *cumulativeTime = entry.cumulativeTime; NSLog(@"Name: %@, Latitude: %@", name, latitude); }If you don't have the subclass (use KVC)
SinceNSManagedObjectsupports Key-Value Coding (KVC), you can usevalueForKey:to pull properties directly:NSArray *entriesArray = // Your existing array for (NSManagedObject *entry in entriesArray) { NSString *name = [entry valueForKey:@"entryName"]; NSString *latitude = [entry valueForKey:@"latitude"]; NSLog(@"Name: %@, Latitude: %@", name, latitude); }
Using initWithEntityName:
Quick note: Apple doesn't provide a built-in initWithEntityName: method for NSManagedObject. The standard way to create a managed object is using [NSEntityDescription insertNewObjectForEntityForName:inManagedObjectContext:] (like we did earlier).
That said, if you want a custom initializer named initWithEntityName:, you can add it to your Entry subclass:
Step 1: Declare the initializer in Entry.h
#import <CoreData/CoreData.h> NS_ASSUME_NONNULL_BEGIN @interface Entry : NSManagedObject @property (nullable, nonatomic, copy) NSString *cumulativeTime; @property (nullable, nonatomic, copy) NSString *latitude; @property (nullable, nonatomic, copy) NSString *entryName; // Custom initializer - (instancetype)initWithEntityName:(NSString *)entityName inContext:(NSManagedObjectContext *)context; @end NS_ASSUME_NONNULL_END
Step 2: Implement it in Entry.m
#import "Entry.h" @implementation Entry @dynamic cumulativeTime; @dynamic latitude; @dynamic entryName; - (instancetype)initWithEntityName:(NSString *)entityName inContext:(NSManagedObjectContext *)context { NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:context]; self = [super initWithEntity:entity insertIntoManagedObjectContext:context]; if (self) { // Set default values if needed self.cumulativeTime = @"0000"; } return self; } @end
How to use it:
NSManagedObjectContext *context = // Get your context Entry *customEntry = [[Entry alloc] initWithEntityName:@"Entry" inContext:context]; customEntry.entryName = @"Bangalore"; // Save the context as before
内容的提问来源于stack exchange,提问作者Hirak Barman

