how to get information of an object instance from ID number - objective-c

I have a program that has 2 tables on two different windows. One table holds the customer name and id number and the other one hold the item name and number. They are both stored in a array and also in a .plist file.
What i would like to do is that on a third page there is going to be a sales page where the user will enter the customer id and item id and the program should be able to find the name and display it to a label. I don't know where to start and go. Could somebody please help or show me how to do i? I can upload any code that anybody wants to see but as I dont know where to start I dont know what to upload.
this is the customer.h file
#import <Foundation/Foundation.h>
NSString *name;
int memberNumber;
#interface Customer : NSObject <NSCoding>
{
NSString *name;
int memberNumber;
}
#property (nonatomic, copy) NSString *name;
#property int memberNumber;
#end
this is the customer.m
#import "Customer.h"
#implementation Customer
#synthesize name;
#synthesize memberNumber;
-(id) init
{
self = [super init];
if(self)
{
name = #"Test";
int i = arc4random()%1000000000000000000;
if (i<0)
{
memberNumber = i*-1;
}
else
memberNumber = i;
}
return self;
}
- (id)initWithCoder:(NSCoder *)decoder
{
if (self = [super init])
{
self.name = [decoder decodeObjectForKey:#"name"];
self.memberNumber = [decoder decodeIntForKey:#"memberNumber"];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder
{
[encoder encodeObject:name forKey:#"name"];
[encoder encodeInt:memberNumber forKey:#"memberNumber"];
}
-(void)dealloc
{
[name release];
[super dealloc];
}
#end
this is the tableView.h file
#import <Foundation/Foundation.h>
#include <stdlib.h>
NSString *filepath;
#interface tableViewData : NSObject <NSTableViewDataSource>
{
#private
IBOutlet NSTableView *tableView;
NSMutableArray *list;
NSString *filepath;
}
-(IBAction)add:(id)sender;
-(IBAction)remove:(id)sender;
#end
this is the tableView.m file
#import "tableViewData.h"
#import "Customer.h"
#implementation tableViewData
-(void)awakeFromNib{
filepath = #"/Users/Desktop/CustomerNames.plist";
if ([[NSFileManager defaultManager]fileExistsAtPath:filepath])
{
NSMutableArray *archive = [NSKeyedUnarchiver unarchiveObjectWithFile:filepath];
list = archive;
}
else
list=[[NSMutableArray alloc]init];
}
-(NSInteger)numberOfRowsInTableView:(NSTableView *)tableView
{
return [list count];
}
-(id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
Customer *Customer = [list objectAtIndex:row];
NSString *identifier = [tableColumn identifier];
return [Customer valueForKey:identifier];
}
-(void)tableView:(NSTableView *)tableView setObjectValue:(id)object forTableColumn: (NSTableColumn *)tableColumn row:(NSInteger)row
{
Customer *Customer = [list objectAtIndex:row];
NSString *identifier = [tableColumn identifier];
[Customer setValue:object forKey:identifier];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:list];
[data writeToFile:filepath options:NSDataWritingAtomic error:nil];
}
-(IBAction)add:(id)sender
{
[list addObject:[[Customer alloc]init]];
[tableView reloadData];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:list];
[data writeToFile:filepath options:NSDataWritingAtomic error:nil];
for (id name in list)
NSLog(#"obj: %#", name);
NSLog (#"array:%#",list);
}
-(IBAction)remove:(id)sender
{
NSInteger row = [tableView selectedRow];
if (row != -1)
{
[list removeObjectAtIndex:row];
}
[tableView reloadData];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:list];
[data writeToFile:filepath options:NSDataWritingAtomic error:nil];
}
-(void)dealloc
{
[super dealloc];
}
#end
hope this helps
(xcode 4.2.1 for OS X)

For example:
if([myNumber isKindOfClass:[NSNumber class]])
{
//do something here
}
That check if object myNumber is a NSNumber class Object. You can use whatever class you want of course. Read the documentation

If items you loaded to table are at the same order in your table you can use
[myArray objectAtIndex:[indexPath row]];
Then use can use the variables of the array that you needed.

First in that code:
-(void)tableView:(NSTableView *)tableView setObjectValue:(id)object forTableColumn: (NSTableColumn *)tableColumn row:(NSInteger)row
{
Customer *Customer = [list objectAtIndex:row];
NSString *identifier = [tableColumn identifier];
[Customer setValue:object forKey:identifier];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:list];
[data writeToFile:filepath options:NSDataWritingAtomic error:nil];
}
change Customer *Customer to Customer *customer ALWAYS use that way.
Then use that method to understand which row is selected.In your case which customer is selected. I understand from your code that every row has a costumer and those customers are in your list array.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//with this code you can get the selected customer from your list,
Customer *customer=[list objectAtIndex:[indexPath row]];
}
Then you can reach the values of the customer.

Related

Access properties and methods from one class inside another class in Objective C

I am trying to build a class in Objective C that contain serve the web service and database methods for my application. In this class I want to call a web service and grab employee records and then load them into an SQL table for later use in a view.
I got this working when all the code as in the view, but in trying to make this new class (what I am calling GetEmployee) I am running into problems. I do not understand well how to access properties and methods from one class in another.
Here is my GetEmployee Class
#import <Foundation/Foundation.h>
#import "employee.h"
#import "FMDatabase.h"
#import "FMDatabaseAdditions.h"
#import "FMDatabasePool.h"
#import "FMDatabaseQueue.h"
#import "FMResultSet.h"
#import "Utility.h"
#interface GetEmployee : NSObject
{
NSMutableArray *employees;
}
#property (nonatomic, copy) NSString *databaseName;
#property (nonatomic, copy) NSString *databasePath;
- (void)updateEmployeeData;
- (void)callWebService;
- (void)fetchedData:(NSData *)responseData;
- (NSMutableArray *) getEmployees;
#end
implementation
#define kBgQueue dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
#define scoularDirectoryURL [NSURL URLWithString: #"https://XXXXXXXXX/mobile/mobilede.nsf/restServices.xsp/PeopleByName"]
#import "GetEmployee.h"
#import "FMDatabase.h"
#import "FMDatabaseAdditions.h"
#import "FMResultSet.h"
#implementation GetEmployee
- (id) init
{
if (self = [super init])
{
self.databaseName = #"employees.db";
}
return self;
}
#pragma
- (void)updateEmployeeData{
//Delete database if it exists and then copy fresh DB
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir = [documentPaths objectAtIndex:0];
self.databasePath = [documentDir stringByAppendingPathComponent:self.databaseName];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL success;
success = [fileManager fileExistsAtPath:self.databasePath];
if (success) {
[fileManager removeItemAtPath:self.databasePath error:nil];
}
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:self.databaseName];
[fileManager copyItemAtPath:databasePathFromApp toPath:self.databasePath error:nil];
//Call the web service
[self callWebService];
[self populateDatabase];
}
- (void) callWebService {
dispatch_sync(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:
scoularDirectoryURL];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
- (void)fetchedData:(NSData *)responseData {
NSError* error;
NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData: responseData options: NSJSONReadingMutableContainers error: &error];
id jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
employees = [[NSMutableArray alloc] init];
if (!jsonArray) {
} else {
for (jsonObject in jsonArray){
employee *thisEmployee = [employee new];
thisEmployee.fullName = [jsonObject objectForKey:#"$13"];
thisEmployee.ste = [jsonObject objectForKey:#"state"];
thisEmployee.city = [jsonObject objectForKey:#"city"];
[employees addObject:thisEmployee];
}
}
}
-(void) populateDatabase {
////Call the web service and populate the db
//dispatch_sync(kBgQueue, ^{
// NSData* data = [NSData dataWithContentsOfURL:
// scoularDirectoryURL];
// [self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
//});
//Populate the db
FMDatabase *db = [FMDatabase databaseWithPath:[Utility getDatabasePath]];
[db open];
for (employee *thisemployee in employees) {
BOOL success = [db executeUpdate:#"INSERT INTO employees (fullname,city,state) VALUES (?,?,?);",thisemployee.fullName,thisemployee.city,thisemployee.ste, nil];
if (success) {} // Only to remove success error
}
[db close];
}
- (NSMutableArray *) getEmployees
{
//NSMutableArray *employees = [[NSMutableArray alloc] init];
employees = [[NSMutableArray alloc] init];
FMDatabase *db = [FMDatabase databaseWithPath:[Utility getDatabasePath]];
[db open];
FMResultSet *results = [db executeQuery:#"SELECT * FROM employees"];
while([results next])
{
employee *thisEmployee = [employee new];
thisEmployee.fullName = [results stringForColumn:#"fullname"];
thisEmployee.city = [results stringForColumn:#"city"];
thisEmployee.ste = [results stringForColumn:#"state"];
[employees addObject:thisEmployee];
}
[db close];
return employees;
}
#end
And here is the MasterViewController
header
#import <UIKit/UIKit.h>
#import "employee.h"
#import "FMDatabase.h"
#import "FMResultSet.h"
#import "FMDatabaseAdditions.h"
#import "Utility.h"
#import "GetEmployee.h"
#interface MasterViewController : UITableViewController
{
NSMutableArray *employees;
//GetEmployee *ScoularEmployees;
}
#end
implementation
#define kBgQueue dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
#define scoularDirectoryURL [NSURL URLWithString: #"https://xxxxxxxx/mobile/mobilede.nsf/restServices.xsp/PeopleByName"]
#import "MasterViewController.h"
#import "DetailViewController.h"
#import "employee.h"
#import "GetEmployee.h"
#interface MasterViewController () {
NSMutableArray *_objects;
}
#property(strong, nonatomic) GetEmployee *ScoularEmployees;
#end
#implementation MasterViewController
- (void)awakeFromNib
{
[super awakeFromNib];
}
- (void)viewDidLoad
{
[super viewDidLoad];
//GetEmployee *ScoularEmployees = [[GetEmployee alloc] init];
[self.ScoularEmployees init];
//[self.ScoularEmployees init];
//_ScoularEmployees = [[GetEmployee alloc] init];
//[_ScoularEmployees getEmployees];
//GetEmployee *ScoularEmployees = [[GetEmployee alloc] init];
//GetEmployee *thisEmployeeData = [[GetEmployee alloc] init];
//[self.ScoularEmployees updateEmployeeData];
//[self.ScoularEmployees getEmployees];
//[ScoularEmployees updateEmployeeData];
//[ScoularEmployees getEmployees];
}
#pragma mark - Table View
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return employees.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
NSString *fullName = [[employees objectAtIndex:indexPath.row] valueForKey:#"fullName"];
cell.textLabel.text = fullName;
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
[_objects removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
} else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"showDetail"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
employee *dtlEmployee = [employees objectAtIndex:indexPath.row];
[[segue destinationViewController] setDetailItem:dtlEmployee];
}
}
- (void)fetchedData:(NSData *)responseData {
NSError* error;
NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData: responseData options: NSJSONReadingMutableContainers error: &error];
id jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
//employees = [[NSMutableArray alloc] init];
if (!jsonArray) {
} else {
//NSMutableArray *employees = [[NSMutableArray alloc ]init];
for (jsonObject in jsonArray){
employee *thisEmployee = [employee new];
thisEmployee.fullName = [jsonObject objectForKey:#"$13"];
thisEmployee.ste = [jsonObject objectForKey:#"state"];
thisEmployee.city = [jsonObject objectForKey:#"city"];
[employees addObject:thisEmployee];
}
}
}
//-(NSMutableArray *) getEmployees
//{
//NSMutableArray *employees = [[NSMutableArray alloc] init];
//employees = [[NSMutableArray alloc] init];
// FMDatabase *db = [FMDatabase databaseWithPath:[Utility getDatabasePath]];
// [db open];
// FMResultSet *results = [db executeQuery:#"SELECT * FROM employees"];
//
// while([results next])
// {
// employee *thisEmployee = [employee new];
// thisEmployee.fullName = [results stringForColumn:#"fullname"];
// thisEmployee.city = [results stringForColumn:#"city"];
// thisEmployee.ste = [results stringForColumn:#"state"];
// //[employees addObject:thisEmployee];
// }
//
// [db close];
//
// return employees;
// return true;
//}
#end
Any help would be greatly appreciated.
I thought it was clear but I can see it is not. In the view class I want to be able to load an NSMutableArray called *employees that comes from the SQLLite database and out them on the screen. I have tried to centralize the code for data access in the GetEmployee class. Everything in that class deals with the data - web service, load the data to the database, and getting the data out of the database as well. So in that Class I have a method "getEmployees" that gets data from the db and loads it into that NSMutableArry. So here is the problem, in the class I cannot get access to the methods or properties in GetEmpployee. That is my question.
Without reading through all the code you've posted...
For using a Class method, the syntax is:
[ClassName methodName];
[ClassName anotherMethod:withArguments];
Methods that are called using this syntax will look like this in the corresponding .h file:
+(void)methodName;
+(void)anotherMethod:(NSNumber*)number;
For using an instance method, the syntax is:
ClassName myObj = [[ClassName alloc] init];
[myObj someMethod];
[myObj someOtherMethod:withArguments];
Methods that are called using this syntax will look like this in the corresponding .h file:
-(void)someMethod;
-(void)someOtherMethod:(NSString*)parameter;

Setting cell.textlabel.text from json array

Hello I'm trying to parse data from json and get the values to show in cells.
Here is my ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
{
IBOutlet UITableView *mainTableView;
NSMutableData *data;
}
#property (nonatomic, strong) NSArray *category;
#property (nonatomic, strong) NSArray *coursesArray;
#property (nonatomic, strong) NSDictionary *parsedData;
#end
This is what I have in ViewController.m
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
parsedData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
coursesArray = [parsedData valueForKey:#"courses"];
NSLog(#"coursesArray: %#", coursesArray);
category = [coursesArray valueForKey:#"category"];
NSLog(#"%#", category);
}
-(int)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MainCell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:#"MainCell"];
}
cell.textLabel.text = [NSString stringWithFormat:#"%#", [category objectAtIndex:indexPath.row]];
NSLog(#"%#", category);
return cell;
}
At connectionDidFinishLoading I see in the log the right values, but when I try to check them before the cell is created I get null.
What I'm doing wrong here?
Call
[mainTableView reloadData];
inside your -connectionDidFinishLoading: method.
Make sure your category array is not released/autoreleased.

UISearchBarDelegate on UITableView with Sections Issue

I'm having issues with implementing the UISearchBarDelegate on my UITableView with sections issue where every time I try to search for something inside the UITableView, either it doesn't display the desired result or it crashes the app with an error saying:
Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
Here's inside my header file:
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, UISearchDisplayDelegate, UISearchBarDelegate>
{
UITableView *mainTableView;
NSMutableArray *contentsList;
NSMutableArray *searchResults;
NSString *savedSearchTerm;
NSMutableArray *ivSectionKeys;
NSMutableDictionary *ivSectionContents;
}
#property (nonatomic, retain) IBOutlet UITableView *mainTableView;
#property (nonatomic, retain) NSMutableArray *contentsList;
#property (nonatomic, retain) NSMutableArray *searchResults;
#property (nonatomic, copy) NSString *savedSearchTerm;
#property (nonatomic, retain) NSMutableArray *sectionKeys;
#property (nonatomic, retain) NSMutableDictionary *sectionContents;
- (void)handleSearchForTerm:(NSString *)searchTerm;
#end
while this is inside my implementation file:
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize mainTableView;
#synthesize contentsList;
#synthesize searchResults;
#synthesize savedSearchTerm;
#synthesize sectionKeys = ivSectionKeys;
#synthesize sectionContents = ivSectionContents;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSMutableArray *keys = [[NSMutableArray alloc] init];
NSMutableDictionary *contents = [[NSMutableDictionary alloc] init];
NSString *colorKey = #"Colors";
NSString *clothingKey = #"Clothing";
NSString *miscKey = #"Misc";
[contents setObject:[NSArray arrayWithObjects:#"Red", #"Blue", nil] forKey:colorKey];
[contents setObject:[NSArray arrayWithObjects:#"Pants", #"Shirt", #"Socks", nil] forKey:clothingKey];
[contents setObject:[NSArray arrayWithObjects:#"Wankle Rotary Engine", nil] forKey:miscKey];
[keys addObject:clothingKey];
[keys addObject:miscKey];
[keys addObject:colorKey];
self.sectionKeys = keys;
self.sectionContents = contents;
// Restore search term
if (self.savedSearchTerm)
{
self.searchDisplayController.searchBar.text = self.savedSearchTerm;
}
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Save the state of the search UI so that it can be restored if the view is re-created.
self.savedSearchTerm = self.searchDisplayController.searchBar.text;
self.searchResults = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self.mainTableView reloadData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)handleSearchForTerm:(NSString *)searchTerm
{
self.savedSearchTerm = searchTerm;
if (self.searchResults == nil)
{
NSMutableArray *array = [[NSMutableArray alloc] init];
self.searchResults = array;
array = nil;
}
[self.searchResults removeAllObjects];
if ([self.savedSearchTerm length] != 0)
{
for (NSString *currentString in self.sectionContents)
{
if ([currentString rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location != NSNotFound)
{
[self.searchResults addObject:currentString];
}
}
}
}
#pragma mark -
#pragma mark UITableViewDataSource Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSInteger sections = [self.sectionKeys count];
return sections;
}
- (NSString *)tableView:(UITableView *)tableView
titleForHeaderInSection:(NSInteger)section
{
NSString *key = [self.sectionKeys objectAtIndex:section];
return key;
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
NSString *key = [self.sectionKeys objectAtIndex:section];
NSArray *contents = [self.sectionContents objectForKey:key];
NSInteger rows;
if (tableView == [[self searchDisplayController] searchResultsTableView])
rows = [self.searchResults count];
else
rows = [contents count];
NSLog(#"rows is: %d", rows);
return rows;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *key = [self.sectionKeys objectAtIndex:indexPath.section];
NSArray *contents = [self.sectionContents objectForKey:key];
NSString *contentForThisRow = [contents objectAtIndex:indexPath.row];
if (tableView == [self.searchDisplayController searchResultsTableView])
contentForThisRow = [self.searchResults objectAtIndex:indexPath.row];
else
contentForThisRow = [contents objectAtIndex:indexPath.row];
static NSString *CellIdentifier = #"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = contentForThisRow;
return cell;
}
#pragma mark -
#pragma mark UITableViewDelegate Methods
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#pragma mark -
#pragma mark UISearchDisplayController Delegate Methods
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString
{
[self handleSearchForTerm:searchString];
// Return YES to cause the search result table view to be reloaded.
return YES;
}
- (void)searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller
{
self.savedSearchTerm = nil;
[self.mainTableView reloadData];
}
#end
I think my issue is inside my for-loop but I'm not really sure.
You need to update all of your table view data source and delegate methods to handle both tables (you only do this in some):
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
NSInteger sections = [self.sectionKeys count];
return sections;
}
should be:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if (tableView == self.tableView) {
NSInteger sections = [self.sectionKeys count];
return sections;
} else { // assume it's the search table
// replace this with the actual result
return numberOfSectionsForSearchTable;
}
}

How to pass data from uitableview to detail view in storyboard

I'm creating my first app in iOS 5 using storyboards. I have a tableviewcontroller embedded in a navigation controller and when you click on the cells in the tableviewcontroller some detail about that cell topic & a URL should be passed to a detail view. I use a PList to populate the tableview. I failed to pass the detail to detail view...
Here is my code (4 classes):
// NormalDataCell.m
#import "NormalDataCell.h"
#implementation NormalDataCell
#synthesize image = _image;
#synthesize nameLabel = _nameLabel;
#synthesize category = _category;
#synthesize webSiteURL = _webSiteURL;
#end
// normalData.m
#import "NormalData.h"
#implementation NormalData
#synthesize name = _name;
#synthesize image = _image;
#synthesize webSiteURL = _webSiteURL;
#synthesize category = _category;
- (id)initWithItem:(NSDictionary *)item {
self = [super init];
if (self) {
_name = [item objectForKey:#"name"];
_image = [UIImage imageNamed:[item objectForKey:#"image"]];
_webSiteURL = [item objectForKey:#"webSiteURL"];
_category = [item objectForKey:#"category"];
}
return self;
}
#end
#implementation NormalCategory
#synthesize category = _category;
#synthesize normalList = _normalList;
- (id)initWithArray:(NSMutableArray *)normalList {
self = [super init];
if (self) {
NSMutableArray *list = [[NSMutableArray alloc]init];
for (NSDictionary *item in normalList) {
NormalData *data = [[NormalData alloc]initWithItem:item];
[list addObject:data];
}
NormalData *data = [list objectAtIndex:0];
_category = data.category;
_normalList = list;
}
return self;
}
#end
// normalViewController.m
#import "NormalViewController.h"
#import "NormalData.h"
#import "NormalDataCell.h"
#import "NormalDetailView.h"
#interface NormalViewController ()
{
#private
NSMutableArray *_cellContentList;
}
#end
#implementation NormalViewController
#synthesize tableView; // Add this line of code
#synthesize roleArray;
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *url = [NSURL URLWithString:#"http://vfttx.web.fc2.com/normal.plist"];
NSMutableArray *array = [NSMutableArray arrayWithContentsOfURL:url];
_cellContentList = [[NSMutableArray alloc]init];
for (NSMutableArray *item in array)
{
NormalCategory *category = [[NormalCategory alloc]initWithArray:item];
[_cellContentList addObject:category];
}
}
//How do I pass the name & webSiteURL to DetailView?
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"TableToWebSegue"]) {
NSIndexPath *path = [self.tableView indexPathForSelectedRow];
NSString *cellName = [[_cellContentList objectAtIndex:path.row] objectForKey:#"name"];
[segue.destinationViewController setDetailItem2:cellName];
NSString *urlPath = [[_cellContentList objectAtIndex:path.row] objectForKey:#"webSiteURL"];
[segue.destinationViewController setWebSiteURL:urlPath];
}
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [_cellContentList count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
NormalCategory *category = [_cellContentList objectAtIndex:section];
return [category category];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NormalCategory *category = [_cellContentList objectAtIndex:section];
return [category.normalList count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"normalDataCell";
NormalDataCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell...
if (cell == nil) {
cell = [[NormalDataCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NormalCategory *category = [_cellContentList objectAtIndex:[indexPath section]];
NormalData *data = [category.normalList objectAtIndex:[indexPath row]];
[cell.nameLabel setText:data.name];
[cell.image setImage:data.image];
cell.webSiteURL = data.webSiteURL;
return cell;
}
#end
// NormalDetailView.m
#import "NormalDetailView.h"
#interface NormalDetailView ()
#end
#implementation NormalDetailView
#synthesize webSiteURL;
#synthesize webView;
#synthesize name = _name;
#synthesize detailItem2;
#synthesize testNameLabel;
- (void)viewDidLoad
{
[super viewDidLoad];
testNameLabel.text = detailItem2;
//If the URL is right, it will work.
NSString *strUrl = webSiteURL;
strUrl = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:strUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
}
#end
Presumably you're using segues to move between the different views.
Implement - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender on the view controller containing your table view and it will be called after the user taps the cell. It contains a reference to the segue object which you can use to find the sourceViewController and the destinationViewController, you can use these to set the data in the destination.

need to save contents of table view as txt file and the reload it later

i need to be able to save the contents of my table view which is given data by an NSMutableArray to a txt file and then need to reopen that file automatically when the window containing the table view. i am making an application for mac
thanks
this is the code for the data source:
#import "tableViewData.h"
#import "Customer.h"
#implementation tableViewData
-(id) init
{
self = [super init];
if (self) {
list = nil;
filepath = #"/Users/Gautambir/Desktop/CustomerNames.txt";
if ([[NSFileManager defaultManager]fileExistsAtPath:filepath]) {
list = [[NSMutableArray alloc] initWithContentsOfFile:filepath];
}
else
list = [[NSMutableArray alloc]initWithObjects:name,memberNumber ,nil];
[list writeToFile:filepath atomically:YES];
}
return self;
}
-(NSInteger)numberOfRowsInTableView:(NSTableView *)tableView{
return [list count];
}
-(id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row{
Customer *Customer = [list objectAtIndex:row];
NSString *identifier = [tableColumn identifier];
return [Customer valueForKey:identifier];
}
-(void)tableView:(NSTableView *)tableView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row{
Customer *Customer = [list objectAtIndex:row];
NSString *identifier = [tableColumn identifier];
[Customer setValue:object forKey:identifier];
}
-(void)save{
[list writeToFile:filepath atomically:YES];
}
-(IBAction)add:(id)sender{
[list addObject:[[Customer alloc]init]];
[tableView reloadData];
NSLog (#"array:%#",list);
}
-(IBAction)remove:(id)sender{
NSInteger row = [tableView selectedRow];
if (row != -1) {
[list removeObjectAtIndex:row];
}
[tableView reloadData];
}
-(void)dealloc
{
[super dealloc];
}
#end
and this is the .m file for the customer object class:
#import "Customer.h"
#implementation Customer
#synthesize name;
#synthesize memberNumber;
-(id) init
{
self = [super init];
if(self) {
name = #"Test";
int i = arc4random()%1000000000000000000;
if (i<0) {
memberNumber = i*-1;
}
else
memberNumber = i;
}
return self;
}
-(void)dealloc
{
[name release];
[super dealloc];
}
-(id)initWithCoder:(NSCoder *)aDecoder
{
self = [super init];
if (self)
{
name = [[aDecoder decodeObjectForKey:#"name"]retain];
memberNumber = [aDecoder decodeIntForKey:#"memberNumeber"];
}
return self;
}
-(void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:name forKey:#"name"];
[aCoder encodeInt:memberNumber forKey:#"memberNumber"];
}
#end
strong text
im sorry to post another answer - i misread the tags, and my first answer was relying to iOS.
this is the way to do it in OSX:
saving
NSMutableArray *array = ... //your array
[array addObject:...];
[array addObject:...];
[array addObject:...];
...
// then use an NSData to store the array
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:array];
NSString *path = #"/Users/User/path...";
[data writeToFile:path options:NSDataWritingAtomic error:nil];
retrieving
NSMutableArray *archive = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
sebastian