I am new in IOS development, i want to write down following scenario in best possible way:
- (void)configureDataSource {
NSMutableArray *meterUnitArray = [[NSMutableArray alloc] init];
NSMutableArray *meterSubUnitArray = [[NSMutableArray alloc] init];
NSMutableArray *footUnitArray = [[NSMutableArray alloc] init];
NSMutableArray *footSubUnitArray = [[NSMutableArray alloc] init];
self.footArray = [[NSMutableArray alloc] init];
self.meterArray = [[NSMutableArray alloc] init];
for(int i = 0; i <= 99; i++)
{
NSString *str = [NSString stringWithFormat:#"%d Meter", i];
NSString *str1 = [NSString stringWithFormat:#"%d cm", i];
[meterUnitArray addObject:str];
[meterSubUnitArray addObject:str1];
NSString *str2 = [NSString stringWithFormat:#"%d Foot", i];
NSString *str3 = [NSString stringWithFormat:#"%d Inches", i];
[footUnitArray addObject:str2];
[footSubUnitArray addObject:str3];
}
[self.meterArray addObject:meterUnitArray];
[self.meterArray addObject:meterSubUnitArray];
[self.footArray addObject:footUnitArray];
[self.footArray addObject:footSubUnitArray];
}
How can i refine this code?
#interface YourClass ()
#property (strong, nonatomic) NSArray *footArray;
#property (strong, nonatomic) NSArray *meterArray;
#end
#implementation YourClass
- (void)configureDataSource {
self.meterArray = #[[#[] mutableCopy], [#[] mutableCopy]];
self.footArray = #[[#[] mutableCopy], [#[] mutableCopy]];
for(int i = 0; i <= 99; i++) {
[self.meterArray[0] addObject:[NSString stringWithFormat:#"%d Meter", i]];
[self.meterArray[1] addObject:[NSString stringWithFormat:#"%d cm", i]];
[self.footArray[0] addObject:[NSString stringWithFormat:#"%d Foot", i]];
[self.footArray[1] addObject:[NSString stringWithFormat:#"%d Inches", i]];
}
}
Related
I'm trying to sort my tableview using NSSortDescriptor in a UISegmentedControl. When I log the Array to sort it shows the correct sorting order, but the tableview doesn't update after calling [self.tableView reloadData];
The data comes from an array which is populated by a json feed. I'm not using NSObjects to display the tableview, it's all populated from the NSArray. See code below:
#interface LinksTableViewController (){
NSArray *data;
}
#property (strong, nonatomic) NSArray *links;
#property (strong, nonatomic) NSArray *tNames;
#property (strong, nonatomic) NSArray *dThor;
#property (strong, nonatomic) NSArray *theLinker;
#property (strong, nonatomic) NSArray *anText;
#property (strong, nonatomic) NSArray *noDo;
#end
#implementation LinksTableViewController
- (void)viewDidLoad {
[super viewDidLoad];
UISegmentedControl *statFilter = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:#"STAT1", #"STAT2", #"STAT3", #"STAT4", nil]];
[statFilter sizeToFit];
[statFilter addTarget:self action:#selector(MySegmentControlAction:) forControlEvents: UIControlEventValueChanged];
self.navigationItem.titleView = statFilter;
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(refreshdelay:) userInfo:nil repeats:NO];
}
- (void)MySegmentControlAction:(UISegmentedControl *)segment
{
NSArray *arrayToSort = data;
if (segment.selectedSegmentIndex == 0)
{
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"pda" ascending:NO];
arrayToSort = [arrayToSort sortedArrayUsingDescriptors:#[sortDescriptor]];
NSLog(#"%#", arrayToSort);
}
else if (segment.selectedSegmentIndex == 1)
{
}
else if (segment.selectedSegmentIndex == 2)
{
}
else if (segment.selectedSegmentIndex == 3)
{
}
[self.tableView reloadData];
}
-(void)refreshdelay:(NSTimer*)timer
{
NSString *myString = [links absoluteString];
NSURL *JSONData = [NSURL URLWithString:myString];
NSData *datas = [NSData dataWithContentsOfURL:JSONData];
NSURLRequest *request = [NSURLRequest requestWithURL:JSONData];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
operation.responseSerializer.acceptableContentTypes = [operation.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSArray *jsonResult = [NSJSONSerialization JSONObjectWithData:datas options:kNilOptions error:nil];
data = jsonResult;
NSMutableArray *names = [NSMutableArray array];
NSMutableArray *bLinks = [NSMutableArray array];
NSMutableArray *daThor = [NSMutableArray array];
NSMutableArray *bsLink = [NSMutableArray array];
NSMutableArray *ancTxt = [NSMutableArray array];
NSMutableArray *folLowd = [NSMutableArray array];
for (id itemfeed in jsonResult){
[names addObject:[NSString stringWithFormat:#"%#", itemfeed[#"ut"]]];
[bsLink addObject:[NSString stringWithFormat:#"%#", itemfeed[#"uu"]]];
[bLinks addObject:[NSString stringWithFormat:#"%#", itemfeed[#"upa"]]];
[daThor addObject:[NSString stringWithFormat:#"%#", itemfeed[#"pda"]]];
[ancTxt addObject:[NSString stringWithFormat:#"%#", itemfeed[#"lt"]]];
[folLowd addObject:[NSString stringWithFormat:#"%#", itemfeed[#"lf"]]];
self.links = names;
self.tNames = bLinks;
self.dThor = daThor;
self.theLinker = bsLink;
self.anText = ancTxt;
self.noDo = folLowd;
}
[self.tableView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
[operation start];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
static NSString *Cellidentifier = #"DataTableCellId";
LICustomCell *cell = (LICustomCell *) [tableView dequeueReusableCellWithIdentifier:Cellidentifier];
if (cell == nil) {
cell = [[LICustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Cellidentifier];
NSArray *nib = [[NSBundle mainBundle]loadNibNamed:#"LiCellView" owner:self options:nil];
cell = nib[0];
NSString *sLink = self.links[indexPath.row];
NSString *aLink = self.tNames[indexPath.row];
NSString *aDa = self.dThor[indexPath.row];
NSString *theInk = self.theLinker[indexPath.row];
NSString *thAnk = self.anText[indexPath.row];
NSString *fLink = self.noDo[indexPath.row];
cell.ageLable.text = theInk;
}
return cell;
}
Looks like the data for your tableView is in 6 different arrays.
NSString *sLink = self.links[indexPath.row];
NSString *aLink = self.tNames[indexPath.row];
NSString *aDa = self.dThor[indexPath.row];
NSString *theInk = self.theLinker[indexPath.row];
NSString *thAnk = self.anText[indexPath.row];
NSString *fLink = self.noDo[indexPath.row];
Shouldn't you be sorting all of them? As your code stands now it's not clear how arrayToSort is connected to the data model of your tableView. You have NSArray *arrayToSort = data;, but it's not clear where data is initialized or where it's set (seems like you would want to set that in your JSON competition block). You also need to call [self.tableView reloadData]; at the end of MySegmentControlAction.
You can create a subclass of NSObject that has 6 NSString properties call it something like MyObject (but more descriptive). Then do something like:
for (id itemfeed in jsonResult){
MyObject *object = [[MyObject alloc]init];
object.sLink = [NSString stringWithFormat:#"%#", itemfeed[#"ut"]];
object.aLink = [NSString stringWithFormat:#"%#", itemfeed[#"uu"]];
...
[self.data addObject:object];
}
In the JSON competition block.
You then change cellForRowAtIndexPath to include something like
MyObject *object = [self.data objectAtIndex:indexPath.row]
cell.ageLable.text = object.theInk;
If you go this route you also need to update:
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"pda" ascending:NO];
specifically #"pda" to whatever you name the property in your NSObject subclass. #"dThor" if you follow the naming I used.
Is there is a better way to convert NSArray of NSString into NSArray of NSNumber than the following code:
-(NSArray*) convertStringArrayToNumberArray:(NSArray *)strings {
NSMutableArray *numbers = [[NSMutableArray alloc] initWithCapacity:strings.count];
for (NSString *string in strings) {
[numbers addObject:[NSNumber numberWithInteger:[string integerValue]]];
}
return numbers;
}
-(NSArray *)convertStringArrayToNumberArray:(NSArray *)strings {
return [strings valueForKeyPath:#"self.integerValue"];
}
I test
NSArray * array = #[#"1",#"2",#"3"];
NSArray *num = [self convertStringArrayToNumberArray:array];
And result
I want to create a table view which is scrollable both horizontally and vertically. I can do this by taking values myself. But I want to take the values from json. I am using model class and my json values are like this:
[
{
"cid": 109,
"iid": 10653,
"yr": 1994,
"val": "15.4311527806175"
},
{
"cid": 109,
"iid": 7872,
"yr": 1999,
"val": "8.84575553637328"
},
{
"cid": 109,
"iid": 7872,
"yr": 1998,
"val": "6.18441582677751"
},
I want my first column to be fixed when scrolling horizontally and first row to be fixed when I scroll it vertically. First column should have iid. first row should have yr and data should have val.
I am using XCMltisortTableView, ASIHttpRequest and SBJson.
I am getting the header value and left column value. How can I get the data corresponding to the yr and iid in proper column?
My code for val in requestFinished method is as follows:
rightTableData = [NSMutableArray arrayWithCapacity:mainTableData.count];
NSMutableArray *right = [NSMutableArray arrayWithCapacity:mainTableData.count];
for (int i = 0; i < mainTableData.count; i++)
{
// Model *model = [mainTableData objectAtIndex:i];
NSMutableArray *array = [NSMutableArray arrayWithCapacity:mainTableData.count];
for (int j = 0; j < headData.count; j++)
{
Model *model = [mainTableData objectAtIndex:j];
if([headData isEqual: #"2000"])
{
[array addObject:[NSString stringWithFormat:#"%#", model.val]];
}
else if([headData isEqual: #"2001"])
{
[array addObject:[NSString stringWithFormat:#"%#", model.val]];
}
else if([headData isEqual: #"2002"])
{
[array addObject:[NSString stringWithFormat:#"%#", model.val]];
}
else if([headData isEqual: #"2003"])
{
[array addObject:[NSString stringWithFormat:#"%#", model.val]];
}
else if([headData isEqual: #"2004"])
{
[array addObject:[NSString stringWithFormat:#"%#", model.val]];
}
else
{
[array addObject:[NSString stringWithFormat:#"%#", model.val]];
}
}
[right addObject:array];
}
[rightTableData addObject:right];
I'm totally new and would a appreciate any answers and any suggestions. Please do reply.
Thanks!
After trying for a long time I got the result using the code below:
-(void) requestFinished: (ASIHTTPRequest *) request
{
NSString *theJSON = [request responseString];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSMutableArray *jsonDictionary = [parser objectWithString:theJSON error:nil];
headData = [[NSMutableArray alloc] init];
NSMutableArray *head = [[NSMutableArray alloc] init];
leftTableData = [[NSMutableArray alloc] init];
NSMutableArray *left = [[NSMutableArray alloc] init];
rightTableData = [[NSMutableArray alloc]init];
for (NSMutableArray *dictionary in jsonDictionary)
{
Model *model = [[Model alloc]init];
model.cid = [[dictionary valueForKey:#"cid"]intValue];
model.iid = [[dictionary valueForKey:#"iid"]intValue];
model.yr = [[dictionary valueForKey:#"yr"]intValue];
model.val = [dictionary valueForKey:#"val"];
[mainTableData addObject:model];
[head addObject:[NSString stringWithFormat:#"%ld", model.yr]];
[left addObject:[NSString stringWithFormat:#"%ld", model.iid]];
}
NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:head];
headData = [[orderedSet array] mutableCopy];
NSOrderedSet *orderedSet1 = [NSOrderedSet orderedSetWithArray:left];
NSMutableArray *arrLeft = [[orderedSet1 array] mutableCopy];
//remove duplicate enteries from header array
[leftTableData addObject:arrLeft];
NSMutableArray *right = [[NSMutableArray alloc]init];
for (int i = 0; i < arrLeft.count; i++)
{
NSMutableArray *array = [[NSMutableArray alloc] init];
for (int j = 0; j < headData.count; j++)
{
/* NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF.iid == %ld", [[arrLeft objectAtIndex:i] intValue]];
NSArray *filteredArray = [mainTableData filteredArrayUsingPredicate:predicate];*/
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF.iid == %ld AND SELF.yr == %ld", [[arrLeft objectAtIndex:i] intValue], [[headData objectAtIndex:j] intValue]];
NSArray *filteredArray = [mainTableData filteredArrayUsingPredicate:predicate];
if([filteredArray count]>0)
{
Model *model = [filteredArray objectAtIndex:0];
[array addObject:model.val];
}
}
[right addObject:array];
}
[rightTableData addObject:right];
}
Hope it helps others.
i am getting data from service which i successfully parse like this
-(NSMutableArray *)clubTypes
{
NSMutableArray *dataArray = [[NSMutableArray alloc] init];
NSString *url = [NSString stringWithFormat:#"%#category",KWSURLList];
NSLog(#"%#",url);
NSDictionary * returnDict = (NSDictionary *) [self callWebService:url];
if([returnDict objectForKey:#"result"])
{
// NSDictionary * returnDictResult = (NSDictionary *) [returnDict objectForKey:#"result"];
NSArray *returnedArray = [returnDict objectForKey:#"data"];
for(NSDictionary *clubDict in returnedArray)
{
ClubTypeDC *clubDC = [[ClubTypeDC alloc] init];
clubDC.clubTypeID = [[clubDict objectForKey:#"Id"] intValue];
clubDC.clubTypeTitle = [clubDict objectForKey:#"tittle"];
clubDC.clubTypeImage = [clubDict objectForKey:#"icons"];
[dataArray addObject:clubDC];
// NSLog(#"%#",proEvents.proEventImage);
}
}
}
but i always get an error bad access in numberOfRowsInSection. can any one tell me why?
Remember always return your array like this
return dataArray;
i edited your code, please check it
-(NSMutableArray *)clubTypes
{
NSMutableArray *dataArray = [[NSMutableArray alloc] init];
NSString *url = [NSString stringWithFormat:#"%#category",KWSURLList];
NSLog(#"%#",url);
NSDictionary * returnDict = (NSDictionary *) [self callWebService:url];
if([returnDict objectForKey:#"result"])
{
// NSDictionary * returnDictResult = (NSDictionary *) [returnDict objectForKey:#"result"];
NSArray *returnedArray = [returnDict objectForKey:#"data"];
for(NSDictionary *clubDict in returnedArray)
{
ClubTypeDC *clubDC = [[ClubTypeDC alloc] init];
clubDC.clubTypeID = [[clubDict objectForKey:#"Id"] intValue];
clubDC.clubTypeTitle = [clubDict objectForKey:#"tittle"];
clubDC.clubTypeImage = [clubDict objectForKey:#"icons"];
[dataArray addObject:clubDC];
// NSLog(#"%#",proEvents.proEventImage);
}
}
return dataArray;
}
return dataArray
in your function at last
and
use this in numberOfRowsInSection...
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([dataArray count] > 0) {
return dataArray.count;
}
else {
return 0;
}
}
I Had an exception in the line [array removeObjectsInArray:toRemove]; in the method below and can't understand what's wrong with it..
- (void) handleDearchForTerm:(NSString *)searchTerm
{
NSMutableArray *sectionsToRemove = [[NSMutableArray alloc] init];
[self resetSearch];
for (NSString *key in _keys)
{
NSMutableArray *array = [_names valueForKey:key];
NSMutableArray *toRemove = [[NSMutableArray alloc] init];
for (NSString *name in array)
{
if ([name rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location == NSNotFound)
[toRemove addObject:name];
}
if ([array count] == [toRemove count])
[sectionsToRemove addObject:key];
[array removeObjectsInArray:toRemove];
}
[_keys removeObjectsInArray:sectionsToRemove];
[_table reloadData];
}
Probably array is just instance of NSArray, but not NSMutableArray, you shall check _names setObject:forKeys:
Change:
NSMutableArray *array = [_names valueForKey:key];
To:
NSMutableArray *array = [[NSMutableArray alloc] initWithArray:[_names valueForKey:key]];
Or:
NSMutableArray *array = [[_names valueForKey:key] mutableCopy];