NSMutableDictionary using objectAtIndex - objective-c

I am new to Xcode and I have created a NSMutableDictionary *dIc with following data:
Keys : ID , Name
Data :
ID = 1, Name = John
ID = 2, Name = Smith
I want to access dIc with specific row. I want this result for example :
Name = Smith.
I tried :
-(void)initiateArrays
{
dIc =[[NSMutableDictionary alloc] init];
}
- (void)viewDidLoad
{
[self initiateArrays];
[self callingWebSrvc];
[super viewDidLoad];
}
-(void)callingWebSrvc
{
NSInteger i=0;
do {
self.selectedRowId = [[mainMenuID objectAtIndex:i]integerValue];
[self getItemListFromWebSrvc];
i++;
} while (i<= mainMenuData.count - 1);
}
-(void) getItemListFromWebSrvc
{
//............ Request ....................................>>>
.
.
.
//............ Response ....................................>>>
NSInteger i = 0;
do {
elm = [xmlDataTable objectAtIndex:i];
//Set Object into Arrays
[dIc setObject:[NSNumber numberWithInt:selectedRowId] forKey:#"Id"];
[dIc setObject:[elm childNamed:#"Name"].value forKey:#"Name"];
NSArray *keys = [rowArray allKeys];
// values in foreach loop
for (NSString *key in keys) {
NSLog(#"%# is %#",key, [dIc objectForKey:key ]);
}
i=i+1;
} while (i <= xmlDataTable.count-1);
}
-(void)showResult
{
NSString *anObject = [[dIc objectForKey:#"Name" ] objectAtIndex:1];
NSLog(#"The Value is = %#",anObject );
}
but it's not working.
when i call [self showResult]; i got the following error:
-[__NSCFString objectAtIndex:]: unrecognized selector sent to instance 0x8b9a7f0
2014-02-26 00:53:57.718 iWish[3311:70b] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString objectAtIndex:]: unrecognized selector sent to instance 0x8b9a7f0'

The problem is this line:
NSString *anObject = [[dIc objectForKey:#"Name" ] objectAtIndex:1];
The first object in this story, [dIc objectForKey:#"Name" ], is an NSString. You are then saying objectAtIndex:1 to an NSString - and that is a no-no.

Related

App keeps crashing creating a PygLatin Game - Objective C

I am new to objective C programming.
I created a PygLatin application but it keeps crashing it. Do tell me if you have spotted any problems with my code.
Terminating app due to uncaught exception 'NSRangeException', reason: ' -[__NSArrayM objectAtIndex:]: index 5 beyond bounds [0 .. 4]'
First throw call stack:
would appreciate all the help I can get thanks! :)
#implementation RootViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.userInputTextField.delegate = self;
self.userInputTextField.text = #"";
}
-(void)print: (NSString*)printWords {
self.resultLabel.text = #"%#", printWords;
}
-(void)charsplitter: (NSArray*)charArraysplitter {
//word selection loop
int indexCount = 0;
for(indexCount = 0; indexCount < charArraysplitter.count; indexCount++)
{
self.wordsToBeSplit = charArraysplitter[indexCount];
NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[self.wordsToBeSplit length]];
[self.wordsToBeSplit enumerateSubstringsInRange:NSMakeRange(0, self.wordsToBeSplit.length)
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
[characters addObject:substring];
}];
[self vowelsComparator:characters];
}
}
-(void)vowelsComparator: (NSArray*)comparator {
self.myVowels = [NSArray arrayWithObjects: #"a", #"e", #"i", #"o",#"u", nil];
int charIndex;
self.subsequentCharCount = 0;
for(charIndex = 0; charIndex < comparator.count; charIndex++)
//loops to find if first character is a vowel
if([self.myVowels containsObject:comparator[0]]){
[self print: self.userInputTextField]; NSLog(#"working fine:");
}else{
//loops to find other vowels
while (self.subsequentCharCount < comparator.count){
self.subsequentCharCount++;
if ([self.myVowels containsObject:comparator[self.subsequentCharCount]]){
//moving the consonants behing the vowels
NSLog(#"working fine:");
NSString *combinedWords = [[self.wordsToBeSplit substringFromIndex:self.subsequentCharCount]stringByAppendingString:[self.wordsToBeSplit substringToIndex:self.subsequentCharCount]];
NSString *completedWord = [combinedWords stringByAppendingString:#"ay"];
[self print: completedWord];
}
};
}
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];//resigns the keyboard every time return button is pressed
return YES;
}
- (IBAction)pygButton:(id)sender
{
self.inputText = [self.userInputTextField.text lowercaseString];//user input is lowercase
NSArray *wordsArray = [self.inputText componentsSeparatedByString: #" "]; //separate words into arrays.
[self charsplitter: wordsArray];
}
#end
put
self.subsequentCharCount++;
at the end of while loop means below
[self print: completedWord];

Objective-c: Use predicate with an object

I have a search bar for my table view and until now I used a predicate to check if the data array contains the search bar value. But now there are objects in my data array and now I don't know how to use the predicate. Here is my code:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF contains [cd] %#", self.controller.searchBar.text];
NSMutableArray *temp = [[NSMutableArray alloc] init];
for (int i = 0; i < [self.data count]; i++) {
Student *student = [[Student alloc] initWithIdentifier:[[self.data objectAtIndex:self.tableView.indexPathForSelectedRow.row] objectForKey:#"id"] name:[[self.data objectAtIndex:self.tableView.indexPathForSelectedRow.row] objectForKey:#"name"] is_public:[[self.data objectAtIndex:self.tableView.indexPathForSelectedRow.row] objectForKey:#"is_public"] password:[[self.data objectAtIndex:self.tableView.indexPathForSelectedRow.row] objectForKey:#"passwort"]];
[temp addObject:student];
}
self.results = [temp filteredArrayUsingPredicate:predicate];
Now it compares the search bar value with the object. But it should compare the search bar value with object.name. How can I do this?
EDIT:
The Student code:
#implementation Student
- (id)initWithIdentifier:(NSString *)identifier name:(NSString *)name is_public:(NSString *)is_public password:(NSString *)password {
self= [super init];
if( self ) {
self.identifier = identifier;
self.name = name;
self.is_public = is_public;
self.password = password;
}
return self;
}
- (NSDictionary*)writableRepresentation {
NSMutableDictionary *writableRepresentation= [NSMutableDictionary dictionaryWithCapacity:4];
[writableRepresentation setValue:self.identifier forKey:#"Identifier"];
[writableRepresentation setValue:self.name forKey:#"Name"];
[writableRepresentation setValue:self.is_public forKey:#"is_public"];
[writableRepresentation setValue:self.password forKey:#"password"];
return writableRepresentation;
}
+ (Student*)studentFromDictionary:(NSDictionary*)dictionaryRepresentation {
return [[Tipprunde alloc] initWithIdentifier:[dictionaryRepresentation valueForKey:#"Identifier"] name:[dictionaryRepresentation valueForKey:#"Name"] is_public:[dictionaryRepresentation valueForKey:#"is_public"] password:[dictionaryRepresentation valueForKey:#"password"]];
}
#end
It don't seem to work with SELF.name. I get the following error:
-[Student objectForKey:]: unrecognized selector sent to instance...

Trying to access data from an array and print it out

I have made an array which I store 5 strings and 1 int into which I then store in to another array.
I'm trying to access and print out an array but it only give me this:
2016-01-11 18:47:55.429 quizgame-chrjo564[3378:145727] (null)
I've tried these alternatives:
NSLog(#"%#", [dataArray objectAtIndex:0]);
NSLog(#"%#", dataArray[0]);
Here is all my code:
#import "ViewController.h"
#interface ViewController ()
{
NSMutableArray *_questions;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self quizStart];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)prepQuestions {
[self question:#"Vad heter jag?" answer1:#"Anton" answer2:#"Christian" answer3:#"Christoffer" answer4:#"Simon" correctAnswer:2];
}
- (void)question:(NSString *)q answer1:(NSString *)a1 answer2:(NSString *)a2 answer3:(NSString *)a3 answer4:(NSString *)a4 correctAnswer:(NSInteger)c {
NSArray *tmpArray = [NSArray arrayWithObjects:
[NSString stringWithString:q],
[NSString stringWithString:a1],
[NSString stringWithString:a2],
[NSString stringWithString:a3],
[NSString stringWithString:a4],
[NSNumber numberWithInteger:c],nil];
NSLog(#"%#", q);
[_questions addObject:tmpArray];
}
- (void)quizStart {
[self prepQuestions];
NSArray *dataArray = [_questions objectAtIndex:0];
NSLog(#"%#", [dataArray objectAtIndex:0]);
}
#end
Thanks in advance
*Updated with error after change:
2016-01-11 19:28:00.816 quizgame-chrjo564[3901:202243] - [__NSCFConstantString objectAtIndex:]: unrecognized selector sent to instance 0x75030
2016-01-11 19:28:00.822 quizgame-chrjo564[3901:202243] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '- [__NSCFConstantString objectAtIndex:]: unrecognized selector sent to instance 0x75030'
You never initialize _questions.
Change this:
[_questions addObject:tmpArray];
to:
if (!_questions) {
_questions = [NSMutableArray array];
}
[_questions addObject:tmpArray];
Also, here's a suggestion to make your code cleaner and easier to read.
Don't needlessly use stringWithFormat:.
Use modern syntax for arrays and dictionaries.
Use modern syntax for number boxing.
In other words, you question:... method can be written as:
- (void)question:(NSString *)q answer1:(NSString *)a1 answer2:(NSString *)a2 answer3:(NSString *)a3 answer4:(NSString *)a4 correctAnswer:(NSInteger)c {
NSArray *tmpArray = #[ q, a1, a2, a3, a4, #(c) ];
NSLog(#"%#", q);
if (!_questions) {
_questions = [NSMutableArray array];
}
[_questions addObject:tmpArray];
}

uisearchbar in grouped section uitable

I've pieced together several tutorials to create a grouped table with sections and I'm now trying to get a uisearchbar to work. the problem I'm having is how to search within the grouped sections.
I've read the similar questions this post suggested but can't
This is the code to create the grouped sections
#import "Job.h" // A model for the data
#import "Address.h" // Another model for the data
- (void)viewDidLoad
{
[super viewDidLoad];
self.theTable.delegate = self;
self.theTable.dataSource =self;
_searchBar.delegate = (id)self;
FMDBDataAccess *db = [[FMDBDataAccess alloc] init];
jobs = [[NSMutableArray alloc] init];
jobs = [db getJobs:1];
_sections = [[NSMutableDictionary alloc] init];
NSMutableArray *jobsTempArray = [db getJobsAsDictionary:1];
BOOL found;
// Loop through the books and create our keys
for (NSDictionary *book in jobsTempArray)
{
NSString *cLong = [book objectForKey:#"addrAddress"];
NSString *c = [cLong substringToIndex:1];
found = NO;
for (NSString *str in [_sections allKeys])
{
if ([str isEqualToString:c])
{
found = YES;
}
}
if (!found)
{
[_sections setValue:[[NSMutableArray alloc] init] forKey:c];
}
}
// Loop again and sort the books into their respective keys
for (NSDictionary *book in jobsTempArray)
{
[[_sections objectForKey:[[book objectForKey:#"addrAddress"] substringToIndex:1]] addObject:book];
}
// Sort each section array
for (NSString *key in [_sections allKeys])
{
[[_sections objectForKey:key] sortUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:#"addrAddress" ascending:YES]]];
}
}
And this is the code that searches
-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{
if(text.length == 0)
{
_isFiltered = FALSE;
}
else
{
_isFiltered = true;
_filteredjobs = [[NSMutableArray alloc] init];
//for (Job* book in jobs)
//for (Job* book in [_sections allKeys])
//for (NSString *food in [_sections allKeys])
for (NSDictionary* book in [_sections allKeys])
{
NSString *addrStr = [book objectForKey:#"addrAddress"];
NSString *postStr = [book objectForKey:#"addrPostcode"];
//NSRange nameRange = [book.jobAddress rangeOfString:text options:NSCaseInsensitiveSearch];
NSRange nameRange = [addrStr rangeOfString:text options:NSCaseInsensitiveSearch];
//NSRange descriptionRange = [book.jobPostcode rangeOfString:text options:NSCaseInsensitiveSearch];
NSRange descriptionRange = [postStr rangeOfString:text options:NSCaseInsensitiveSearch];
if(nameRange.location != NSNotFound || descriptionRange.location != NSNotFound)
{
[_filteredjobs addObject:book];
}
}
}
[self.theTable reloadData];
}
I've got as far as realising I need to change for (Job* food in jobs) to for (NSDictionary* book in [_sections allKeys]) but I'm stuck how to search within [_sections allKeys]
Specifically this line
NSRange nameRange = [addrStr rangeOfString:text options:NSCaseInsensitiveSearch];
which crashes with
-[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x692e200
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString objectForKey:]:
unrecognized selector sent to instance 0x692e200':
Any ideas? PS Treat me as a noob, I'll need some code as well as explanation - I'm still learning obj-c
Check the Link.It shows the UISearchBar With Grouped Section Tableview.Its a simple Tutorial..Hope its useful for you
I found the answer in
UISearchBar - search a NSDictionary of Arrays of Objects and reading up on allkeys.
Basically loop through the grouped NSDictionary and extract the NSArrays, then loop through again searching...
-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{
if(text.length == 0)
{
_isFiltered = FALSE;
}
else
{
_isFiltered = true;
_filteredjobs = [[NSMutableArray alloc] init];
NSString *currentLetter = [[NSString alloc] init];
for (int i=0; i<[_sections count]; i++)
{
currentLetter = [[_sections allKeys] objectAtIndex:i];
NSArray *jobsForKey = [ [NSArray alloc] initWithArray:[_sections objectForKey:[[_sections allKeys] objectAtIndex:i]] ];
for (int j=0; j<[jobsForKey count]; j++)
{
NSDictionary *book = [jobsForKey objectAtIndex:j];
NSRange titleResultsRange = [[book objectForKey:#"addrAddress"] rangeOfString:text options:NSCaseInsensitiveSearch];
if(titleResultsRange.location != NSNotFound)
{
[_filteredjobs addObject:book];
}
}
}
}
[self.theTable reloadData];
}

[__NSCFString objectAtIndex:]: unrecognized selector sent to instance Error

I tried loading the contents of the bucket into a NSTableView using Arraycontroller. I ended uo with this error:
-[__NSCFString objectAtIndex:]: unrecognized selector sent to instance 0x1006da970
Here is the code I used to check.
- (IBAction)checkCloud:(id)sender {
AmazonS3Client *s3 = [AmazonClientManager s3];
S3ListObjectsRequest* listObjectsRequest = [[S3ListObjectsRequest alloc] initWithName:#"hello-testing"];
NSMutableArray *fileListCloud = [[NSMutableArray alloc] init];
NSMutableArray *fileModifiedList = [[NSMutableArray alloc] init];
#try {
S3ListObjectsResponse* response = [s3 listObjects:listObjectsRequest];
NSMutableArray* objectSummaries = response.listObjectsResult.objectSummaries;
for ( S3ObjectSummary* objSummary in objectSummaries ) {
[fileListCloud addObject:[objSummary key]];
[fileModifiedList addObject:[objSummary lastModified]];
}
}
#catch (NSException *exception) {
NSLog(#"Cannot list S3 %#",exception);
}
[self loadFileListTable:fileListCloud andFileModificationDate:fileModifiedList];
}
-(void)loadFileListTable:(NSMutableArray *)fileListArray andFileModificationDate:(NSMutableArray *)modifiedArray{
NSRange range = NSMakeRange(0, [[_fileListAC arrangedObjects] count]);
[_fileListAC removeObjectsAtArrangedObjectIndexes:[NSIndexSet indexSetWithIndexesInRange:range]];
for(int i = 0 ; i<[fileListArray count];i++){
[_fileListAC addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:[[fileListArray objectAtIndex:i] objectAtIndex:0],#"Files",[[modifiedArray objectAtIndex:i] objectAtIndex:1],#"Date Modified", nil]];
}
}
The array is loaded with with file names but when i add it to the array controller it throws the above mentioned error. Any help would be really great.
Here
[[fileListArray objectAtIndex:i] objectAtIndex:0]
[[modifiedArray objectAtIndex:i] objectAtIndex:1]
[fileListArray objectAtIndex:i] and [modifiedArray objectAtIndex:i] are not NSArrays (I think they are both NSStrings).
You just need to remove the erroneous objectAtIndex:0 and objectAtIndex:1 messages.
Change here
[_fileListAC addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:[fileListArray objectAtIndex:i],#"Files",[modifiedArray objectAtIndex:i], #"Date Modified", nil]];