I have a array of ProductData as follows, and I want to filter them based on their category and I applied the following Predicate, but it returns me error.
pTempElements =[[NSMutableArray alloc] initWithArray: [self.pElements filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"category = %#", #"4"]]];
Terminating app due to uncaught exception 'NSUnknownKeyException',
reason: '[ valueForUndefinedKey:]: this class
is not key value coding-compliant for the key category.'
Here is overlook of the pElements
po self.pElements
<__NSArrayM 0x174241e30>(
<ProductData: 0x17427ce00>,
<ProductData: 0x17427cd80>,
<ProductData: 0x17427ce40>,
<ProductData: 0x17427ce80>,
)
ProductData.m
#import "ProductData.h"
#implementation ProductData
#synthesize pId, pImage, pPrice, pName, pCategory
-(id)initWithDictionary:(NSDictionary *)aDict{
self = [self init];
if (self){
self.pId = [aDict objectForKey:#"id"];
self.pPrice = [aDict objectForKey:#"price"];
self.pImage = [aDict objectForKey:#"imagePath"];
self.pCategory = [aDict objectForKey:#"category"];
self.pName = [aDict objectForKey:#"name"];
}
return self;
}
You should give the property name of the object by which you planning to filter the array. Here I guess it is pCategory. You should rewrite your code as below
pTempElements =[[NSMutableArray alloc] initWithArray: [self.pElements filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"pCategory == %#", #"4"]]];
Related
I am receiving error:
Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[__NSCFConstantString
subjectType]: unrecognized selector sent to instance
I am trying to sort students in my app to arrays by the subject type that they are learning.
AMStudent* student = [[AMStudent alloc] init];
NSMutableArray* studentArray = [[NSMutableArray alloc] init];
NSArray* studentNameArray = [NSArray arrayWithObjects: #"Student1", #"Student2", #"Student3", #"Student4", #"Student5", #"Student6", #"Student7", #"Student8", #"Student9", #"Student10", nil];
[studentArray addObjectsFromArray:studentNameArray];
for (NSInteger i = 0; i < [studentNameArray count]; i++) {
student.name = [studentNameArray objectAtIndex: i];
[student randomAnswer];
NSLog(#"%#", student.description);
}
NSMutableArray* techArray = [NSMutableArray array];
NSMutableArray* humArray = [NSMutableArray array];
for (AMStudent* stud in studentArray){
if ((stud.subjectType & AMStudentSubjectTypeDevelopment) | (stud.subjectType & AMStudentSubjectTypeMath)) {
[techArray addObject:stud];
} else {
[humArray addObject:stud];
}
}
I cant figure out what exactly I am doing wrong, because it crashes in this stage:
if ((stud.subjectType & AMStudentSubjectTypeDevelopment) | (stud.subjectType & AMStudentSubjectTypeMath)) {
[techArray addObject:stud];
} else {
[humArray addObject:stud];
}
You are calling
stud.subjectType
in the studentArray after copying the studentNames (NSString) to the student array:
[studentArray addObjectsFromArray:studentNameArray];
NSString won't recognize subjectType.
You fill studentArray using:
[studentArray addObjectsFromArray:studentNameArray];
So studentArray contains NSString instances. You then attempt to process the array using:
for (AMStudent* stud in studentArray){
This does not magically convert the NSString instances in studentArray into AMStudent instances. You don't get an error at this point as studentArray can contain objects of any type so the compiler just trusts you know what you are doing and places a reference to an NSString into stud. You then do:
if ((stud.subjectType ...
and this requires stud to reference an AMStudent object, which it does not, it references a (constant) string and so you get the error:
NSInvalidArgumentException', reason: '-[__NSCFConstantString subjectType]: unrecognized selector sent to instance
Instead of copying the names of the students into studentArray you need to create instances of AMStudent and add those to the array. Did you intend to do that in the first loop maybe?
HTH
techArray and humArray (NSArray) type change not working add object function.
NSMutableArray *newtechArray = [techArray mutableCopy];
NSMutableArray *newhumArray = [humarray mutableCopy];
if ((stud.subjectType & AMStudentSubjectTypeDevelopment) | (stud.subjectType & AMStudentSubjectTypeMath)) {
[newtechArray addObject:stud];
} else {
[newhumArray addObject:stud];
}
Thanks a lot for Your wide answer, I understood my mistake. Just added one more loop and added object student.
for (NSInteger numberOfStudents = 0; numberOfStudents < 10; numberOfStudents ++){
AMStudent* student = [[AMStudent alloc] init];
student.name = [studentNameArray objectAtIndex:numberOfStudents];
}
[studentArray addObject:student];
I have a custom object which contains data as:
#interface Students : NSObject
{
}
#property (nonatomic,strong) NSString *ID;
#property (nonatomic,strong) NSString *FirstName;
#property (nonatomic,strong) NSString *MiddleName;
#property (nonatomic,strong) NSString *LastN
I want to filter it according to the last name. For example:
I want an array which contains all the details of students having last name="Cena"
I tried this:
NSMutableArray *arrayToFilter = self.studentList;
NSString *nameformatString = #"LastName contains[c] a";
NSPredicate *namePredicate = [NSPredicate predicateWithFormat:nameformatString];
[arrayToFilter filterUsingPredicate:namePredicate];
When I run my app I am getting this error and my app crashes:
Terminating app due to uncaught exception 'NSUnknownKeyException', reason:
'[< Students 0x7fd25e102d20> valueForUndefinedKey:]:
this class is not key value coding-compliant for the key a.'
I am only able to get last name in array but I know this is wrong. How can I sort the custom object based on last name.
Code I am using to get lastName:
names = [[NSMutableArray alloc]init];
for (int i = 0; i < [self.studentList count] ; i++)
{
Students * studentsObj = (Students*)[self.studentList objectAtIndex:i];
[names addObject:studentsObj.LastName];
}
Update the predicate to ,
NSString *textToMatch = #"a";
NSPredicate *namePredicate = [NSPredicate predicateWithFormat:#"LastN CONTAINS[cd] %#", textToMatch];
then
NSMutableArray *arrayToFilter = self.studentList;
NSArray *filteredArray = [arrayToFilter filteredArrayUsingPredicate:namePredicate];
for getting last name only,
NSArray *lastNames = [filteredArray valueForKey:#"LastN"];
NSArray *sortedArray = [lastNames sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
following snippet gives me :
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '- [__NSCFString count]: unrecognized selector sent to instance 0x8ce0c00'
-(void)loadInfo{
// Create the query.
NSString *query = [NSString stringWithFormat:#"select * from tableName where category=\"%#\" ", #"cat1"];
// Load the relevant data.
NSArray *results = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];
NSMutableArray *List = [[NSMutableArray alloc]init];
NSLog(#"Count..:%d",results.count);
for(int i=0; i<results.count; i++){
List = [[results objectAtIndex:i] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:#"itemName"]];
}
NSLog(#"Result..:::: %d", [List count]);
}
What is going wrong here? Cant i print List count? dbmanager is what I have implemented using eg. given in - http://www.appcoda.com/sqlite-database-ios-app-tutorial/
This operation replaces List on every loop iteration with a different object:
List = [[results objectAtIndex:i] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:#"itemName"]];
Judging from the error, the object happens to be NSString.
What you probably wanted is to add objects to your mutable array List:
[List addObject:[[results objectAtIndex:i] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:#"itemName"]]];
Hello guys I am new to Xcode/iOS developing
I trying to add json data to the mutable array , and it results in app crash :(
so far here is my code:
if(! [defaults objectForKey:#"Person1"])
[defaults setObject:[PersonsFromSearch objectAtIndex:index] forKey:#"Person1"];
else
{
NSMutableArray *Array = [[NSMutableArray alloc]init];
id object = [defaults objectForKey:#"Person1"];
Array = [object isKindOfClass:[NSArray class]] ? object : #[object];
[Array addObject:[PersonsFromSearch objectAtIndex:index]];//crash here :((
[Array moveObjectFromIndex:[Array count] toIndex:0];
}
Crash Dump:
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI addObject:]: unrecognized selector sent to instance 0xcb4d380'
* First throw call stack:
what is wrong here ? can you please help me to resolve this issue
Array contains this (Json?)
{
Address = "\U05d3\U05e8\U05da \U05d4\U05e9\U05dc\U05d5\U05dd 53";
CellPhone = "052-3275381";
EMail = "editor#pc.co.il";
EnglishPerson = "Yehuda Konfortes";
FaceBookLink = "";
Fax1 = "03-7330703";
Fax2 = "";
FileNAme = "100050.jpg";
HomeEMail = "";
HomeFax = "";
HomePhone1 = "";
HomePhone2 = "";
PersonID = 100050;
PersonName = "\U05d9\U05d4\U05d5\U05d3\U05d4 \U05e7\U05d5\U05e0\U05e4\U05d5\U05e8\U05d8\U05e1";
Phone1 = "03-7330733";
Phone2 = "";
ZipCode = "";
}
[defaults objectForKey:#"Person1"]; returns dictionary but not array.
So you can't use addObject method.
UPD
You may resolve this crash by creation array with a single object.
Here is updated code:
NSMutableArray *Array = [[NSMutableArray alloc]init];
id object = [defaults objectForKey:#"Person1"];
Array = [object isKindOfClass:[NSArray class]] ? [object mutableCopy] : [#[object] mutableCopy];
[Array addObject:[PersonsFromSearch objectAtIndex:index]];//crash here :((
[Array moveObjectFromIndex:[Array count] toIndex:0];
NSMutableArray *_arr = [[NSMutableArray alloc]init];
NSDictionary *results = PASS JSON Value;
[_arr add object:[results objectforkey:#“Address”]];
[_arr add object:[results objectforkey:#“CellPhone”]];
I have a global NSMutableArray and I need to update it with values. NSMutableArray is defined in the .h as follows;
#property (strong, nonatomic) NSMutableArray *myDetails;
In the viewDidLoad pre-populate like this;
NSDictionary *row1 = [[NSDictionary alloc] initWithObjectsAndKeys:#"1", #"rowNumber", #"125", #"yards", nil];
NSDictionary *row2 = [[NSDictionary alloc] initWithObjectsAndKeys:#"2", #"rowNumber", #"325", #"yards", nil];
NSDictionary *row3 = [[NSDictionary alloc] initWithObjectsAndKeys:#"3", #"rowNumber", #"525", #"yards", nil];
self.myDetails = [[NSMutableArray alloc] initWithObjects:row1, row2, row3, nil];
Then when the user changes a text field this code is run this;
-(void)textFieldDidEndEditing:(UITextField *)textField{
NSObject *rowData = [self.myDetails objectAtIndex:selectedRow];
NSString *yards = textField.text;
[rowData setValue:yards forKey:#"yards"];
[self.myDetails replaceObjectAtIndex:selectedRow withObject:rowData];
}
When stepping through the code on the line [rowData setValue:yards forKey:#"yards"]; it returns this error;
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'
The array is mutable, but what is in it... NSDictionary... is not. You grab an object out of the array...
NSObject *rowData = [self.myDetails objectAtIndex:selectedRow];
and then you try to mutate that object...
[rowData setValue:yards forKey:#"yards"];
The object in the array is the thing you are changing... and it is NSDictionary, immutable, and you can not change it. If you want the dictionary to be mutable, you have to use NSMutableDictionary