Storing a history list in objective c - iphone

I am doing a project to scan qr codes.a.
In this project a history page is present in which i have to show the history of user's scans.
It contains URLs only. So I am planning to show the list of urls he scanned previously in a table view.
How can i save the history list? help, please. can I use NSMutable array or something to save the scanned urls like this[myArray writeToURL:aURL atomically:NO];

yes for this you have to create a internel database using sqlite or coredata wherever user scan the qrcode store into database and wherever user wants to see history then fetch from database and display whatever method you use to dispaly

NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingString:#"/"];
NSString *fullPathToFile = [filePath stringByAppendingPathComponent:#"myfile.plist"];
[myArray writeToFile:fullPathToFile atomically:YES];

Yes you can.
Your table view needs to implement a UITableViewDataSource to use the NSMutableArray as the source of your table view: (here using myArray as the array in this sample code)
-(void)saveToHistoryArray:(NSString *)urlAsString {
[myArray addObject:urlAsString];
[self.tableView reloadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
/* insert error checking here */
return [myArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [myArray objectAtIndex:indexPath.row];
return cell;
}

Related

Populating UITableView with NSArray in iOS 7

A lot of the methods have deprecated in iOS 7 in order to set font, textLabel, and color for UITableView cells. I'm also just having a difficult time populating the view with these values. Here's a snippet of my code:
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSArray* jobs = [json objectForKey:#"results"];
for(NSDictionary *jobsInfo in jobs) {
JobInfo *jobby = [[JobInfo alloc] init];
jobby.city = jobsInfo[#"city"];
jobby.company = jobsInfo[#"company"];
jobby.url = jobsInfo[#"url"];
jobby.title = jobsInfo[#"jobtitle"];
jobby.snippet = jobsInfo[#"snippet"];
jobby.state = jobsInfo[#"state"];
jobby.time = jobsInfo[#"date"];
jobsArray = [jobsInfo objectForKey:#"results"];
}
}
I am looping through an array of dictionaries from a GET request and parsed. I am now attempting to fill my UITableView with the following code:
-
(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [jobsArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSDictionary *jobsDic = [jobsArray objectAtIndex:indexPath.row];
[cell.textLabel setText:[jobsDic objectForKey:#"jobtitle"]];
return cell;
}
Also, I have declared this is in my .h file:
NSArray *jobsDic;
Any ideas on what I'm doing wrong? Is this an iOS 7 problem?
It seems that you reinitialize jobsarray at the end of the forin loop.
You didn't mean ?
NSArray* jobs = [json objectForKey:#"results"];
NSMutableArray *jobsTemp = [[NSMutableArray alloc] initWithCapacity:jobs.count];
for(NSDictionary *jobsInfo in jobs) {
JobInfo *jobby = [[JobInfo alloc] init];
jobby.city = jobsInfo[#"city"];
jobby.company = jobsInfo[#"company"];
jobby.url = jobsInfo[#"url"];
jobby.title = jobsInfo[#"jobtitle"];
jobby.snippet = jobsInfo[#"snippet"];
jobby.state = jobsInfo[#"state"];
jobby.time = jobsInfo[#"date"];
[jobsTemp addObject:jobby];
}
self.jobsArray = jobsTemp; //set #property (nonatomic, copy) NSArray *jobsArray; in the .h
[self.tableView reloadData]; //optional only if the data is loaded after the view
In the cell for row method :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
JobInfo *job = self.jobsArray[indexPath.row];
cell.textLabel.text = job.title;
return cell;
}
And don't forget :
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.jobsArray.count;
}
Update - an user suggested an edit :
It's true that count isn't a NSArray property. But as Objective-C lets us use a shortcut notation for calling method with a dot, this code works. You have to know limitation of this : if you use a NSArray subclass with a count property with a custom getter this could have side effects #property (nonatomic, strong, getter=myCustomCount) NSUInteger count. As I think code readability is to me one of most important things I prefer to use dot notation. I think Apple SHOULD implement count as readonly property so I use it this way (but it's my point of view). So for those which don't agree with me just read return [self.jobsArray count]; in the tableView:numberOfRowsInSection: method.
Change the declaration of jobsArray from NSArray to NSMutableArray.
Add an initialization at the beginning point of fetchedData method like follows.
if(!jobsArray) {
jobsArray = [NSMutableArray array];
}
else {
[jobsArray removeAllObjects];
}
Remove the following line.
jobsArray = [jobsInfo objectForKey:#"results"];
Instead of that, add the initialized object to the array at the end of for loop.
[jobsArray addObject:jobby];
Add a [tableView reloadData]; at the end of your *-(void)fetchedData:(NSData )responseData; method implementation.
Initially when you are loading the view, tableView will get populated. After you received the data, tableView will not be known that it is received.
Everything else seems good. Hope rest will work fine.

Array not showing in Table View

Can anyone tell me why my code isn't showing any results in my table view. Here is my code. I already tried to change the #"#" into indexPath.row without any luck. I 'm looking for any answer into the right direction. I'm fairly new to xcode and objective-c. I would really appreciate any help.
-(void)waitAndFillPlaylistPool {
// arrPlaylist -> mutablearray which stores the value of loaded playlist in order to use it later
[SPAsyncLoading waitUntilLoaded:[SPSession sharedSession] timeout:kSPAsyncLoadingDefaultTimeout then:^(NSArray *loadedession, NSArray *notLoadedSession)
{
// The session is logged in and loaded — now wait for the userPlaylists to load.
NSLog(#"[%# %#]: %#", NSStringFromClass([self class]), NSStringFromSelector(_cmd), #"Session loaded.");
[SPAsyncLoading waitUntilLoaded:[SPSession sharedSession].userPlaylists timeout:kSPAsyncLoadingDefaultTimeout then:^(NSArray *loadedContainers, NSArray *notLoadedContainers)
{
// User playlists are loaded — wait for playlists to load their metadata.
NSLog(#"[%# %#]: %#", NSStringFromClass([self class]), NSStringFromSelector(_cmd), #"Container loaded.");
NSMutableArray *playlists = [NSMutableArray array];
[playlists addObject:[SPSession sharedSession].starredPlaylist];
[playlists addObject:[SPSession sharedSession].inboxPlaylist];
[playlists addObjectsFromArray:[SPSession sharedSession].userPlaylists.flattenedPlaylists];
[SPAsyncLoading waitUntilLoaded:playlists timeout:kSPAsyncLoadingDefaultTimeout then:^(NSArray *loadedPlaylists, NSArray *notLoadedPlaylists)
{
// All of our playlists have loaded their metadata — wait for all tracks to load their metadata.
NSLog(#"[%# %#]: %# of %# playlists loaded.", NSStringFromClass([self class]), NSStringFromSelector(_cmd),
[NSNumber numberWithInteger:loadedPlaylists.count], [NSNumber numberWithInteger:loadedPlaylists.count + notLoadedPlaylists.count]);
NSLog(#"loadedPlaylists >> %#",loadedPlaylists);
arrPlaylist = [[NSMutableArray alloc] initWithArray:loadedPlaylists];
NSLog(#"arrPlaylist >> %#",arrPlaylist);
}];
}];
}];
}
- (NSInteger) tableView:(UITableView *) tableView numberOfRowsInSection:(NSInteger)section {
return [arrPlaylist count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [arrPlaylist objectAtIndex:indexPath.row];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
It's hard to tell what you're doing in the method, waitAndFillPlaylistPool, but if this is taking any time to get this data, then you need to call reloadData on your table view ([self.tableView reloadData]) as the last line in that method (or when any async method returns -- I can't tell where that might be in your code).

NSMutableArray not updating and UITableView not reloading

I'm creating a chat application. I have 2 methods in my view controller one for sending and one for receiving the messages. In the sending method i create a NSMutableDictionary with two objects ..
NSMutableDictionary *msgFilter = [[NSMutableDictionary alloc] init];
[msgFilter setObject:messageStr forKey:#"msg"];
[msgFilter setObject:#"you" forKey:#"sender"];
[messages addObject:msgFilter];
"messages" is my main NSMutableArray for holding all the messages, whose property is set and synthesized and allocated. When i send the message it is properly added into the NSMutableArray and the UITableView is updated showing me the values in the cell.
I have a method in my appDelegate to check for messages received and use the same procedure to parse the data and store it in an NSMutableDictionary. This dictionary is then passed to the viewcontroller and added into the same NSMutableArray(messages) and i then call [self.chattable reloadData]. But this doesn't do anything. When i nsloged the NSMutableArray it only had the received message not the whole data(send + received).
Why is it not adding the received messages into the same array and why is it not refreshing my table. I've been trying to get it to work for days now...Plz help..
//Recives message section
NSMutableDictionary *msgFilter = [myDelegate msgFilter];
[messages addObject:msgFilter];
[self.tView reloadData];
//Tableview section
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [messages count];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
NSDictionary *s = (NSDictionary *) [messages objectAtIndex:indexPath.row];
NSString *sender = [s objectForKey:#"sender"];
NSString *message = [s objectForKey:#"msg"];
if ([sender isEqualToString:#"you"])
{
cell.detailTextLabel.text = [NSString stringWithFormat:#"TX: %at", message];
}
else
{
cell.detailTextLabel.text = [NSString stringWithFormat:#"RX: %at", message];
}
return cell;
}
Declare messages array in Application Delegate. so it will be shared array. so might be your problem get solved. because it is shared array. so you can add Dictionary in messages array from any where, no need to pass dictionary between diff UIView.

Table View Crashing When Accessing Array of Dicitonarys

All,
When my table view loads, it accesses several delegate methods. When I configure the cell, I have it calling this method (where "linkedList" is an array of dictionarys):
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
VUWIManager *vuwiManager = [VUWIManager sharedVuwiManager];
NSLog(#"%#", [[vuwiManager linkedList]objectAtIndex:indexPath.row]);
NSLog(#"TESTZOMGOFDSOJFDSJFPODJSAPFDS");
cell.textLabel.text = [[vuwiManager linkedList]objectAtIndex:indexPath.row];
return cell;
}
It crashes at the line cell.textLabel.text = [[vuwiManager linkedList]objectAtIndex:indexPath.row]; - I know I'm doing something wrong here but I'm not sure what it is. Again, linkedList is a NSMutableArray of NSDictionarys.
Edit: if I call cell.textLabel.text = [[vuwiManager linkedList]objectAtIndex:indexPath.row]; it returns:
{
IP = "192.168.17.1";
desc = "description";
}
in the debugger. Just thought I'd give a little bit of formatting details.
Thanks
You are trying to assign an object NSDictionary to cell.textLabel.text, which must be passed a NSString.
Did you want :
NSString *s = [NSString stringWithFormat:#"%#",
[[vuwiManager linkedList]objectAtIndex:indexPath.row]];
cell.textLabel.text = s;
?
Setting an NSString * to an NSDictionary * will likely result in a crash when it tries to access any string methods that are not implemented in the dictionary. If you want that string you are logging add a call to description.
cell.textLabel.text = [[[vuwiManager linkedList]objectAtIndex:indexPath.row] description];
It looks like you are setting cell.textLabel.text to a NSDictionary instead of an NSString. If linkedList is an NSMutableArray of NSDictionaries, then you need to add on objectForKey:#"String key" to access the string
cell.textLabel.text = [[[vuwiManager linkedList]objectAtIndex:indexPath.row] objectForKey:#"STRING_KEY_HERE"];

how to retrieve values from nsdictionary in iphone?

i am using a function to fill dictionary in a array
here is the code
-(void)getAllFlashCardsNames
{
if ([listofitems count]==0)
listofitems = [[NSMutableArray alloc] init];
else
[listofitems removeAllObjects];
for(int i=0;i<listOfCategoryId.count;i++)
{
int j=[[listOfCategoryId objectAtIndex:i]intValue];
[self getFlashCard:j];
NSArray *flashCardsNames = flashCardsNamesList;
NSArray *flashCardsids = flashCardsId;
NSLog(#"FLash Card Ids %#",flashCardsids);
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:flashCardsNames,#"flashCards",flashCardsids,#"flashCardId",nil];
[listofitems addObject:dictionary];
}
}
in the above code the array flashcardsNamesList,flashCardsId changes everytime when calling the function [self getFlashCard:j]; j is a parameter to change categoryid which comes from the listOfCategoryId array..
now how do i retrieve values from the dictionary i want to show different flashcardsNames on different sections in uitableview.
here is the code i m using to retrieve values
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [listofitems count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection: (NSInteger)section {
NSDictionary *dictionary =[listofitems objectAtIndex:section];
NSLog(#"dictionary=%#",dictionary);
NSArray *array =[dictionary objectForKey:#"flashCards"];
NSLog(#"array=%#",array);
NSLog(#"Section Count = %d",array.count);
return array.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
CustomCell *cell = (CustomCell *)[tableViewdequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
NSDictionary *dictionary =[listofitems objectAtIndex:indexPath.section];
NSArray *array =[dictionary objectForKey:#"flashCards"];
NSArray *array1=[dictionary objectForKey:#"flashCardId"];
NSString *cellValue=[array objectAtIndex:indexPath.row];
NSString *cellValue1=[array1 objectAtIndex:indexPath.row];
[cell.FlashCardsNames setText:cellValue];
[cell setFlashCardId:[cellValue1 intValue]];
return cell;
}
but the method
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath does not get called
but the method -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath does not called
Have you set the object that your method is implemented in as the data source of your table view? UITableView hands some of the work off to another object, which must conform to the UITableViewDataSource and UITableViewDelegate protocols; you must then set the object as the dataSource and delegate of the table view, either in IB or programmatically (the data source and delegate can be different objects, but are commonly the same object). Take a look at this article which explains more about it; once this has been done, your object must handle the tableView:cellForRowAtIndexPath: and tableView:numberOfRowsInSection: methods, which will be called on your object by the table view.
Also, the lines:
if ([listofitems count]==0)
listofitems = [[NSMutableArray alloc] init];
do not make sense. I assume you are checking whether the array has been allocated or not, and if not, to allocate it. If the array hasn't been allocated, it will be nil, so sending count to it will have no effect anyway. If it has been allocated previously, but deallocated but not reverted back to nil it will be a bad pointer and cause your application to crash.
A better way to allocate it would be to do so in your class's awakeFromNib method, or applicationDidFinishLaunching: method, if you are implementing this in your UIApplicationDelegate subclass. Don't forget to release it in your dealloc method.