I want to create an index for my tableView songsTable with the quick-jump index on the right. songsTable displays the contents of songsArray, which shows a list of songs from the user's iPod library:
However, all tutorials that show how to index a tableView already know their contents. These are the tutorials I've seen so far: AppCoda, iPhoneDevCentral, Innofied, among a few others. They all use NSDictionaries to store their contents, I'm using an NSArray.
I tied to follow the AppCode tutorial and I got stuck at the first hurdle:
-(void)createAlphabetArray
{
self.alphabetArray = [[NSMutableArray alloc]initWithCapacity:26];
for (int i=0; i< songs.count; i++)
{
NSString *firstletter=[[songs objectAtIndex:i]substringToIndex:1];
if (![self.alphabetArray containsObject:firstletter]) {
[self.alphabetArray addObject:firstletter];
}
}
[songs sortUsingSelector:#selector(localizedCaseInsensitiveCompare:)]; //sorting array in ascending array
NSLog(#"%#", self.alphabetArray);
}
I'm really, really confused and I can't find any other tutorials that are useful for this situation. Any help would be much appreciated. Thanks.
EDIT: I say 'unknown contents' because I don't know what the contents of songsArray is, like the other tutorials, which actually provide the content of the tables.
You can't add objects to NSArray one by one. You can either add them all in one line, or copy an array to your array.
What you're probably looking for is NSMutableArray instead of NSArray.
This allows you to add objects at will.
You was probably supposed to implement the logic inside loop slightly different:
NSString *firstLetter = [songsArray[i] substringToIndex:1];
if (![self.alphabetArray containsObject:firstLetter]) {
[self.alphabetArray addObject:firstLetter];
}
UPDATE
This would help you to fix the crash. But I don't still understand what do you mean under unknown content. I don't see anything related to this problem in the provided code.
Related
I am new in iOS so please help me. I am getting some messages from server with a key "messageId". I am showing those messages in tableview. Now I have to differentiate that if there is new message which is being open first time in that tableview, I have to change the colour of that message in the cell.
cell.notificationMessageDate.text = [[self.notifications objectAtIndex:indexPath.row] valueForKey:#"msgCreatedDate"];
cell.notificationMessageText.text = [self stringByStrippingHTML:[[self.notifications objectAtIndex:indexPath.row] valueForKey:#"message"]];
NSString *str = [[self.notifications objectAtIndex:indexPath.row] valueForKey:#"messageId"];
self.isAlreadyExist = false;
if (str ) {
cell.backgroundColor = [UIColor whiteColor];
} else {
}
#AADi i see that you are getting message from notifications. I dont know what structure you have implemented.
To implement what you want, what i feel is you must implement a dictionary or array where you store your data from wherever you are fetching it. Then pass the count of the array or dict. to table. Now maintain a variable which stores the previous count of the array or dict. In cell for row, compare the index path with the previous count of the array or dict. If the index path is greater then previous count simply change the background for the cell at that index path and update the value of previous count with current count.
If you don't understand or have any doubts then ask here.
Hope it will help you.
A word of advice, its not a good approach to check if message is new locally. If a user uninstalls the app and reinstall it then all the messages would appear new to the user even thought she may have read them.
A better approach is to send boolean variable, something like seen or read, along with other details of message from the server and display the cells accordingly. To mark a message as read or seen you can make an API call to the server with the messageID reflecting it in the backend.
I am doing a Facebook API request to give me back all the names of the albums from a particular Facebook group. I get back an array of dictionaries with 3 keys/values, one of which being the key 'name' which maps to the album name, along with the keys 'id' and 'created_time'.
Only problem is that for some reason i'm getting back duplicate 'name' values of albums... but only a couple. And when i go to the Facebook page there's only one instance of that album anyway, no duplicates.
Also, their 'id' values are different, but it's only the first dictionary from the group of duplicates that has a Facebook id that actually points to valid data, the other Facebook id values just don't return anything when you perform a Facebook graph search with them, so it's the first of the duplicates that i want.
How can i remove these useless duplicate dictionaries from my array and keep the one with a valid Facebook id?? Thanks! :)
First I'd like to say that it's probably more beneficial to find a way to get a 'clean' list from faceBook as opposed to covering up problems afterwards. This might not be possible right now, but at least find out what the reason is for this behaviour or file a bug report.
Barring that, this should do the trick:
-(NSMutableArray *) groupsWithDuplicatesRemoved:(NSArray *) groups {
NSMutableArray * groupsFiltered = [[NSMutableArray alloc] init]; //This will be the array of groups you need
NSMutableArray * groupNamesEncountered = [[NSMutableArray alloc] init]; //This is an array of group names seen so far
NSString * name; //Preallocation of group name
for (NSDictionary * group in groups) { //Iterate through all groups
name =[group objectForKey:#"name"]; //Get the group name
if ([groupNamesEncountered indexOfObject: name]==NSNotFound) { //Check if this group name hasn't been encountered before
[groupNamesEncountered addObject:name]; //Now you've encountered it, so add it to the list of encountered names
[groupsFiltered addObject:group]; //And add the group to the list, as this is the first time it's encountered
}
}
return groupsFiltered;
}
I have a program that retrieves data from a link and i write it out to the Log like this.
NSURL *getURL=[NSURL URLWithString:#"link.php"];
NSError *error=nil;
NSString *str=[NSString stringWithContentsofURL:getURL encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%",str);
This prints to the log the three values from my php as expected.
However I am having a little difficulty saving this in an array which then displays it those values in a UISplitviewController (the leftcontroller side).
which is written like this
showArray=[[NSMutableArray alloc]initWithContentofURL:getURL];
then in cellForRowAtIndexPath: method is
cell.textLabel.text=[showArray object atIndex:indexPath.row];
A second thing i have tried is write myURL to an array and tried to initlize showArray with ContentsofArray like this
NSArray *retults=[NSArray arraywithContentsOFURL:getURL];
showArray=[[NSArray alloc]initWithArray:retults];
but THAT dont work
BUT if i say
showArray=[[NSMutableArray alloc]initWithObjects:#"One",#"Two",nil];
One and two shows in my leftview controller....
Would love is someone could help me with this...Thank you
Are you trying to add the contents of the URL or the URL itself ?
If you are trying to just add the URL, then use :
showArray = [#[getURL] mutableCopy];
However, if you are trying to add the contents of the URL, then the doc clearly states that the URL must represent a string representation of an array.
Furthermore :
Returns nil if the location can’t be opened or if the contents of the location can’t be parsed into an array.
EDIT :
I saw your comment on your post and your data looks like JSON data.
You should take a look at the NSJSONSerialisation class which is pretty straightforward to use (you'll find lots of example here on SO).
U have done web services perfectly, now wat u have to do is parse it to an array
First download the SBJSON files in this link
https://github.com/stig/json-framework/
Then, copy them to your workspace.
Then, in the viewController add this
#import "SBJson.h"
Your JSON data contains values in the form of dictionary
SO, to parse them
SBJsonParser * parser=[SBJsonParser new];
NSDictionary * jsonData=(NSDictionary *)[parser objectWithString:outputData];
NSArray * arr=(NSArray *)[NSDictionary objectForKey:#"animal"];
I think this will help
I have created the news app which use the "UIScrollView + UIWebView" to let users to swipe through different news. However, I would like to ask whether it's possible for me to add the advertisements like the BBC News app or not, which users will see the advertisements while scrolling horizontally.
I was trying to use addSubView while scrolling (scrollViewDidScroll) but it replaces the existing content.
I realize BBC News app do the things like this,
Users swipe through the news --> After swiping a few times --> show the ads (in position 5, for instance) --> users swipe from start to the end again --> the ads appear again, but this time could be in position 3).
But I just don't know how to make it work for my app. Any clue? thanks in advance.
You probably already have a functionality, where You have stored news articles data in some array. Or You fetch data from database into some array.
Well - I think the easiest way would be just to add advert_data in this news array.
For example - You fetch from db in array:
NSArray *mArray = #[
"news1",
"news2",
"news3",
"news4",
"news5",
"news6"];
then You could simply - iterate it all through, and add advert data. For example
int counter = 0;
while (counter < [mArray count])
{
int mTmp = 3+(arc4random() % 2); // atleast 3, but up to 5?
counter +=mTmp;
[mArray insertObject:"advert" atIndex:counter];
counter +=1; //we added one object, so we need to adjust counter
}
Then simply - when You try to load corresponding data in webview, check if content is not "advert". If it is - load some random advert html from somewhere.
P.S. I guess, Your data arrays will have NSManagedObjects, instead of strings. Then You can check if [mArray objectAtIndex:i] (when You try to load it into webview)- is NSManagedObject or a string value.
I hope You understand this idea.
I am creating an iOS app which reads in a text file and displays the contents in a UIText field.
For the 1st three consecutive runs of thee app (Restarting a new session without exiting),
the data is read in fine. However on the fourth attempt, the data returned from the file is all nulls.
I've verified the file integrity. The issue exists when using stringWithContentsOfFile or initWithContentsOfFile.
After many hours of troubleshooting, I believe the issue is somehow related to a buffer being cleared within the above mentioned methods.
Any insight regarding this issue is greatly appreciated. I've tried many things with no luck.
Here's the code I use to read in the file:
TheString = [NSString stringWithContentsOfFile:[[NSBundle mainBundle]
pathForResource:#"My_TextFile" ofType:#"txt"] encoding:NSUTF8StringEncoding error:NULL];
Here's the code I use to display certain contents of the file (The contents are placed in an array of type NSArray):
NSArray *My_Array;
My_Array= [TheString componentsSeparatedByString:#"\n"];
/* Obtain specific data to display */
DisplayedData = [My_Array objectAtIndex:M[l]-1];
:
:
/* Display the data in the view */
MyUITextView.text = DisplayedData;
/* Log the data */
NSLog(#"%#", MyUITextView.text);
On the 4th invocation of the code above, the data returned is blank and NSLOG is returning nulls
Thanks so much for any help!
Maybe I'm a little bit late with answer, but, anyway, maybe somebody will find it useful.
OK, I have also spent a day trying to figure out why my custom class for scrollable view is working 3 times and refuse at the 4-th time... I found that the problem has quite the same attributes as yours: nested NSString objects unexpectedly disappear. Though pointers point to the same address in memory, memory is already filled with quite arbitrary objects instead my NSStrings.
And I paid attention that I created these NSStrings using the following class method:
+ (id)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error
So, I'm not the owner of these NSStrings.
And I assumed that to be the owner can be a solution, so I created my NSStrings through alloc and
- (id)initWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error
instance method.
App was repaired!