Christie Christie - 1 year ago 84
iOS Question

Why can't I set a variable on my custom class?

I'm creating my first iOS app in Swift, and I'm stuck on a basic thing. I want to create a custom class and set a variable. I keep seeing the error "Value of type [Item] has no member [name].

This is my custom class:

import UIKit
import Foundation
import CoreData

class Item:NSManagedObject {

var name:String?

convenience init(name: String?, insertIntoManagedObjectContext context: NSManagedObjectContext!) {
let entity = NSEntityDescription.entityForName("ItemEntity", inManagedObjectContext: context)!
self.init(entity: entity, insertIntoManagedObjectContext: context)

And this is my code that tries to use it:

func editItem(id:Int, category:String, brand:String, name:String, colour:String, purchasePrice:String, purchaseDate:String, expiryDate:String) -> Int {

// vars
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let entity = NSEntityDescription.entityForName("ItemEntity", inManagedObjectContext: managedContext)
let item = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)
var listItem = [Item]()
let fetchRequest = NSFetchRequest(entityName: "ItemEntity")

// fetch the item from the core data with the same ID
let predicate = NSPredicate(format: "id == %@", String(id))
fetchRequest.predicate = predicate
fetchRequest.fetchLimit = 1
let results = try managedContext.executeFetchRequest(fetchRequest)
listItem = results as! [Item]
catch {
let fetchError = error as NSError
print (fetchError)

// edit the item = "text" // !! THIS IS THE LINE WHICH DISPLAYS THE ERROR

// save the item
do {
catch {
let saveError = error as NSError
print (saveError)


Really appreciate your help, this one seems so basic but a lot of googling hasn't helped me figure it out.

Answer Source

listItem is an array of Item, so if you want to change the name of one thing in this list you should specify the index you wanna change, like

listItem[0].name = "text"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download