If JSON response is "true", don't show results in Table View - ios

I'm getting this JSON:
{
"timestamp": "2013-05-03T22:03:45Z",
"resultsOffset": 0,
"status": "success",
"resultsLimit": 10,
"breakingNews": [],
"resultsCount": 341,
"feed": [{
"headline": "This is the first headline",
"lastModified": "2013-05-03T21:33:32Z",
"premium": false,
"links": {
"api": {
And use this to load it in a UITableView:
#property (strong, nonatomic) NSArray *headlinesArray;
- (void)viewDidLoad
{
[[RKObjectManager sharedManager] loadObjectsAtResourcePath:[NSString stringWithFormat:#"/now/?leafs=%#&teas=%#&apikey=xxxxx", leafAbbreviation, teaID] usingBlock:^(RKObjectLoader *loader) {
loader.onDidLoadObjects = ^(NSArray *objects){
premiumArray = objects;
[_tableView reloadData];
};
[loader.mappingProvider setMapping:[Feed mapping] forKeyPath:#"feed"];
loader.onDidLoadResponse = ^(RKResponse *response){
//NSLog(#"BodyAsString: %#", [response bodyAsString]);
};
}];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"standardCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
Feed *feedLocal = [headlinesArray objectAtIndex:indexPath.row];
NSString *headlineText = [NSString stringWithFormat:#"%#", feedLocal.headline];
cell.textLabel.text = headlineText;
return cell;
}
Headline class model:
#property (strong, nonatomic) NSString *headline;
#property (strong, nonatomic) Links *linksHeadline;
Is there any way to check if premium is true in the JSON, to not show the headline in the UITableView?
EDIT 1
I added #property (strong, nonatomic) NSArray *premiumArray; which is pulling in the correct data associated with premium, so now I just need help looking thru that array for links that say TRUE so my UITableView won't show any headlines that premium = TRUE.
EDIT 2
I posted the viewDidLoad code above.
EDIT 3
Feed.h
#property (nonatomic, strong) NSString *headline;
#property (nonatomic, strong) NSString *premium;
Feed.m
+ (RKObjectMapping *)mapping {
RKObjectMapping *objectMapping = [RKObjectMapping mappingForClass:[self class] usingBlock:^(RKObjectMapping *mapping) {
[mapping mapKeyPathsToAttributes:
#"headline", #"headline",
#"premium", #"premium",
nil];
}];
return objectMapping;
}
EDIT
I added this per some answers, but still couldn't get it working, any thoughts?
#property (strong, nonatomic) NSArray *premiumArray;
#property (strong, nonatomic) NSMutableArray *myMutable;
[[RKObjectManager sharedManager] loadObjectsAtResourcePath:[NSString stringWithFormat:#"/now/?leagues=%#&teams=%#&apikey=5qqpgrsnfy65vjzswgjfkgwy", leagueAbbreviation, teamID] usingBlock:^(RKObjectLoader *loader) {
loader.onDidLoadObjects = ^(NSArray *objects){
//sports = objects;
premiumArray = objects;
[_tableView reloadData];
};
[loader.mappingProvider setMapping:[Feed mapping] forKeyPath:#"feed"];
loader.onDidLoadResponse = ^(RKResponse *response){
//NSLog(#"BodyAsString: %#", [response bodyAsString]);
};
}];
self.myMutable = [[premiumArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"premium = YES"]] mutableCopy];

You will need to create some sort of UITableView data source. Having the UITableView handle this is much more difficult than simply setting up a data structure and then pass that data in to the UITableView data source.
A NSMutableArray would work just fine for what you need done. Whatever JSON parser toolkit you are using, you are likely given an arrayed response, which looks like is stored in headlinesArray, each containing the example code above.
You simply need to enumerate through headlinesArray and IF the [post objectForKey:#"premium"] == TRUE then add it to the NSMutableArray.
Place all of this in the viewDidLoad so that it is processed before the UITableView is built and then in the TableView you simply need to access that newly built array.
.h
#interface YourClass: YourClassSuperclass
{
NSMutableArray *a;
}
.m
//In ViewDidLoad
a = [NSMutableArray array]; //Allocs and Inits a new array.
for (Feed *f in headlinesArray) //For all feeds in the headlines array. (f is the local var)
{
//check if premium == TRUE. If yes, add to a.
}
//Then in your data source methods you just use the array named 'a'
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"standardCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
Feed *feedLocal = [a objectAtIndex:indexPath.row]; //Replaced headlinesArray with a
NSString *headlineText = [NSString stringWithFormat:#"%#", feedLocal.headline];
cell.textLabel.text = headlineText;
return cell;
}

In your table view data source, you will want an NSMutableArray. When you get the data, use this:
NSArray *someFeedArray = ...;
self.mutableArray = [[NSMutableArray alloc] init];
for (NSDictionary *dict in someFeedArray)
{
BOOL isPremium = [[[(NSArray *)dict[#"feed"] objectAtIndex:0] objectForKey:"premium"] boolValue] isEqualToString:#"true"]; //Assuming stored as string
if (!isPremium) [self.mutableArray addObject:dict];
}
In your numberOfRowsInSection method, you should do this:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.mutableArray.count;
}
And you're done.

Related

Update UI table View from a Static method

I am developing a chat application. Some of my classes are singleton therefore I have use lot of static methods.
When ever a new message is received in app delegate. It should send it to my incomingChat viewController.
I am able to get the new message to static method in viewcontroller. But I cant reload the table from static method.
InCommingVC.h
#import <UIKit/UIKit.h>
#interface InCommingVC : UIViewController
#property (weak, nonatomic) IBOutlet UINavigationBar *navigationBarTitle;
#property (weak, nonatomic) IBOutlet UITableView *incommingTable;
+ (void) sendIncommingChats:(NSDictionary *) chatDetails;
+ (void) recieveIncomingChat:(NSDictionary *) chatDetails;
#end
InCommingVC.m
#import "InCommingVC.h"
#import "AppDelegate.h"
#import "IncommingItemObject.h"
static NSMutableArray *incomminglist;
#interface InCommingVC (){
AppDelegate *delegate;
}
#end
#implementation InCommingVC
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationBarTitle.topItem.title = #"Incomming Chats";
}
+ (void) recieveIncomingChat:(NSDictionary *) chatDetails{
NSLog(#"GOT A NEW recieveIncomingChat");
NSString *CompanyId = [chatDetails objectForKey:#"CompanyId"];
NSString *ConnectionId = [chatDetails objectForKey:#"ConnectionId"];
NSString *CountryCode = [chatDetails objectForKey:#"CountryCode"];
NSString *Department = [chatDetails objectForKey:#"Department"];
NSString *Name = [chatDetails objectForKey:#"Name"];
NSString *StartTime = [chatDetails objectForKey:#"StartTime"];
NSString *TimeZone = [chatDetails objectForKey:#"TimeZone"];
NSString *VisitorID = [chatDetails objectForKey:#"VisitorID"];
NSString *WidgetId = [chatDetails objectForKey:#"WidgetId"];
NSLog(#"------------------------------------------------------------------------------");
NSLog(#"CompanyId : %#" , CompanyId);
NSLog(#"ConnectionId : %#" , ConnectionId);
NSLog(#"CountryCode : %#" , CountryCode);
NSLog(#"Department : %#" , Department);
NSLog(#"Name : %#" , Name);
NSLog(#"StartTime : %#" , StartTime);
NSLog(#"TimeZone : %#" , TimeZone);
NSLog(#"VisitorID : %#" , VisitorID);
NSLog(#"WidgetId : %#" , WidgetId);
NSLog(#"------------------------------------------------------------------------------");
IncommingItemObject *item = [[IncommingItemObject alloc] init];
[item setCompanyId:CompanyId];
[item setConnectionId:ConnectionId];
[item setCountryCode:CountryCode];
[item setDepartment:Department];
[item setName:Name];
[item setStartTime:StartTime];
[item setTimeZone:TimeZone];
[item setVisitorID:VisitorID];
[item setWidgetId:WidgetId];
if (incomminglist.count == 0) {
incomminglist = [[NSMutableArray alloc] init];
[incomminglist addObject:item];
[[InCommingVC incommingTable] reloadData];
} else {
[incomminglist addObject:item];
}
NSLog(#"count %i", incomminglist.count);
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return incomminglist.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *cellIdentifier = #"identify_incomming";
UITableViewCell *cell = [self.incommingTable dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
IncommingItemObject *item = [incomminglist objectAtIndex:indexPath.row];
UIImageView *CountryImage = (UIImageView *)[cell viewWithTag:5010];
[CountryImage setImage:[UIImage imageNamed:item.CountryCode]];
UILabel *visitorName = (UILabel *)[cell viewWithTag:5011];
visitorName.text = item.Name;
UILabel *visitStartTime = (UILabel *)[cell viewWithTag:5012];
visitStartTime.text = item.StartTime;
return cell;
}
I want to update my incommingTable from a static method. can some one help me. tnx.
I am having this error
/Users/zupportdesk/Desktop/MyIOSApps/Chat System/Chat
System/InCommingVC.m:96:23: No known class method for selector
'incommingTable'
while doing
[[InCommingVC incommingTable] reloadData];
2 ways :
1 - Make a shared instance. Call :
[[[self class] sharedInstance].tableView reloadData];
2 - Make you class confirm to some notification , that you'll send upon receiving message with payload (chat dictionary). Make sure to deregister the notification when view controller de-allocates
[self.incommingTable reloadData];
Try this please and make sure IBOUTLET is proper connected

NSPredicate issue with NSObjects IOS

I have an NSObject:
#interface ContactAlphaB : NSObject
+ (ContactAlphaB *)contactWithFirstName:(NSString *)firstName lastName:(NSString *)lastName username:(NSString *)username
linkAvatar:(NSString *)linkAvatar registerType:(NSString *)registerType
email:(NSString *)email mobile:(NSString *)mobile;
#end
I had save all informations in this object.
#property (nonatomic) NSString *firstName;
#property (nonatomic) NSString *lastName;
#property (nonatomic) NSString *username;
#property (nonatomic) NSString *linkAvatar;
#property (nonatomic) NSString *registerType;
#property (nonatomic) NSString *stremail;
#property (nonatomic) NSString *strmobile;
And I had show in tableView
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
return self.sectionIndexTitles;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [self.sectionIndexTitles count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSString *sectionIndexTitle = self.sectionIndexTitles[section];
return [self.alphabetizedDictionary[sectionIndexTitle] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
CellListsFriend *cell = [tableView dequeueReusableCellWithIdentifier:#"cellListsFriend" forIndexPath:indexPath];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
ContactAlphaB *contact = [self objectAtIndexPath:indexPath];
cell.lblNameFriend.text = contact.fullName;
// Rounded Rect for cell image
cell.imgAvatarFriends.layer.borderWidth=2;
cell.imgAvatarFriends.layer.borderColor=[[UIColor whiteColor]CGColor];
[cell.imgAvatarFriends.layer setCornerRadius:cell.imgAvatarFriends.frame.size.width/2];
[cell.imgAvatarFriends.layer setMasksToBounds:YES];
return cell;
}
- (void)setContacts:(NSArray *)contacts {
self.alphabetizedDictionary = [CGLAlphabetizer alphabetizedDictionaryFromObjects:contacts usingKeyPath:#"lastName"];
self.sectionIndexTitles = [CGLAlphabetizer indexTitlesFromAlphabetizedDictionary:self.alphabetizedDictionary];
[self.tableView reloadData];
}
- (ContactAlphaB *)objectAtIndexPath:(NSIndexPath *)indexPath {
NSString *sectionIndexTitle = self.sectionIndexTitles[indexPath.section];
return self.alphabetizedDictionary[sectionIndexTitle][indexPath.row];
}
With this code, I can show all myfriend lists in tableView.
And now, I want to do search function (search my friend).
So, I'm using NSPredicate *filter = [NSPredicate predicateWithFormat:#"SELF == %#", searchString]; to work this function.
But, I cannot use filteredArrayUsingPredicate in NSObject to search.
How to I can do search function.
Please help me!
*****************Edited:
NSArray *arr = [FriendList MR_findAll];
if (arr.count > 0) {
for (int i = 0; i < arr.count; i++) {
FriendList *friendList = [arr objectAtIndex:i];
[delegate.arrFriendListsAdded addObject:friendList.username];
ContactAlphaB *contact = [ContactAlphaB contactWithFirstName:friendList.firstName
lastName:friendList.lastName
username:friendList.username
linkAvatar:friendList.avatar
registerType:[NSString stringWithFormat:#"%#", friendList.registerType]
email:friendList.email
mobile:friendList.phoneNumber
];
[_mucontacts addObject:contact];
}
}
_mucontacts is NSMutableArray.
When I log this array:
<__NSArrayM 0x4e48050>(
<ContactAlphaB: 0x4f55b90>,
<ContactAlphaB: 0x13e8dc0>,
<ContactAlphaB: 0x4f2bd30>,
<ContactAlphaB: 0x4e6a490>
)
It is save object. When Search, I want to search lastname.
So, When I search lastname it is get empty.
try with this
NSString *searchString = #"your last name here";
NSPredicate *lastname = [NSPredicate predicateWithFormat:#"self.lastname contains[cd] %#", searchString];
NSArray *filteredArray = [mucontacts filteredArrayUsingPredicate:lastname];

Multi level categories with items on all levels in UITableView

I have to create a UITableView using the JSON response below ( Array ). I have no code for this yet but would love some direction to how i would split this array to accommodate categories and items on all levels.
{
"result":{
"products":[
{
"id":"4",
"product_code":"PR04",
"title":"Product1",
"franchisee_id":"118"
}
],
"categories":[
{
"id":"8",
"name":"Category1"
},
{
"id":"20",
"name":"Category2",
"products":[
{
"id":"9",
"product_code":"PR07",
"title":Product2,
"franchisee_id":"118"
}
]
}
]
}
}
I want to achieve the following result:
items
Category1 > items
Category2 > items
When a category is clicked it would slide to the products in that category. Would really love some direction on this. Some products will not be in categories. Like the example above.
Well....
You need to parse the JSON file. You can easily google for some tutorials but here is a decent one.
Next you are going to need to setup a UITableView to load the items. another good tutorial on UITableViews
Then you are going to need to learn how to pass data between UIViewControllers. Tutorial.
So your steps in the code will be to:
Parse the JSON to separate all the elements.
Setup a UITableView to display the top level elements.
Create a second UITableViewController to push to after a top level item has been selected.
Setup a custom initializer for the second UITableViewController so you can pass it relevant data from the first view controller where you parsed the JSON.
I'm assuming you were looking for a bunch of code on how to do this, but that's no fun :)
Let me know if you run into any troubles and I will be glad to help.
EDIT:
I know I said I wasn't going to dump code but I have some extra time.
Create an NSObject subclass called ProductObject and make the .h look like this:
#import <Foundation/Foundation.h>
#interface ProductObject : NSObject
#property NSString *productCode, *productTitle, *franchiseId, *productId;
#end
Don't do any thing to the .m
Create another NSObject subclass called CategoryObject and make the .h look like this:
#import <Foundation/Foundation.h>
#interface CategoryObject : NSObject
#property NSString *categoryName, *categoryId;
#property NSArray *products;
#end
Again, don't need to do anything to the .m.
Now, in the class that you want to display the UITableView will the Products and Categories (this is all in the .m, the .h is empty):
#import "ViewController.h"
#import "CategoryObject.h"
#import "ProductObject.h"
#interface ViewController ()
//Hooked in from IB
#property (weak, nonatomic) IBOutlet UITableView *table;
//Our UITableView data source
#property NSMutableDictionary *tableObjects;
#end
#implementation ViewController
/**
Parses a the local JSON file
*/
- (void)parseJSON {
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"test" ofType:#"json"];
//création d'un string avec le contenu du JSON
NSString *myJSON = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
NSError *error;
NSDictionary *topLevleJSON = [NSJSONSerialization JSONObjectWithData:[myJSON dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&error];
if (error) {
NSLog(#"Error serializing JSON: %#", error.localizedDescription);
return;
}
NSArray *products = topLevleJSON[#"products"];
NSArray *categories = topLevleJSON[#"categories"];
//Use a NSDictonary so that it contains an NSArray of ProductObjects for the "Products" key, and an array of CategoryObjects for the "Category" key.
self.tableObjects = [NSMutableDictionary new];
//Parse all the products
NSMutableArray *productsInJSON = [NSMutableArray new];
[products enumerateObjectsUsingBlock:^(NSDictionary *productObject, NSUInteger idx, BOOL *stop) {
ProductObject *product = [self createProductObjectFromDictionary:productObject];
[productsInJSON addObject:product];
}];
//Set the array of ProductObjects for the key #"Products"
[self.tableObjects setObject:productsInJSON forKey:#"Products"];
//Parse all the categories
NSMutableArray *categoriesInJSON = [NSMutableArray new];
[categories enumerateObjectsUsingBlock:^(NSDictionary *categoryObject, NSUInteger idx, BOOL *stop) {
CategoryObject *category = [self createCategoryObjectFromDictionary:categoryObject];
[categoriesInJSON addObject:category];
}];
//Set the array of CategoryObjects for key #"Categories"
[self.tableObjects setObject:categoriesInJSON forKey:#"Categories"];
[self.table reloadData];
}
/**
Creates a ProductObject from an NSDictonary.
#param dictionary The dictonary describing the Product parsed from JSON
#return A pretty formatted ProductObject
*/
- (ProductObject*)createProductObjectFromDictionary:(NSDictionary*)dictionary {
ProductObject *product = [ProductObject new];
product.productTitle = dictionary[#"title"];
product.productCode = dictionary[#"product_code"];
product.franchiseId = dictionary[#"franchisee_id"];
product.productId = dictionary[#"id"];
return product;
}
/**
Creates a Category from an NSDictionary
#param dictionary The dictonary describing the Category parsed from JSON
#return A pretty formatted CategoryObject
*/
- (CategoryObject*)createCategoryObjectFromDictionary:(NSDictionary*)dictionary {
CategoryObject *category = [CategoryObject new];
category.categoryId = dictionary[#"id"];
category.categoryName = dictionary[#"name"];
//Check to see if the "products" key exist for the category, if we don't check and just look for it, we will get a crash if it doesn't exist.
if ([[dictionary allKeys] containsObject:#"products"]) {
NSArray *categoryProducts = dictionary[#"products"];
//Parse all the Products for the Category.
NSMutableArray *categoryProductsFormatted = [NSMutableArray new];
[categoryProducts enumerateObjectsUsingBlock:^(NSDictionary *productObject, NSUInteger idx, BOOL *stop) {
ProductObject *product = [self createProductObjectFromDictionary:productObject];
[categoryProductsFormatted addObject:product];
}];
category.products = [NSArray arrayWithArray:categoryProductsFormatted];
}
else {
category.products = nil;
}
return category;
}
#pragma mark -
#pragma mark - UITableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [[self.tableObjects allKeys] count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//Get the key for this section
NSString *key = [[self.tableObjects allKeys] objectAtIndex:section];
//Return the number of objects for this key.
return [(NSArray*)[self.tableObjects objectForKey:key] count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [[self.tableObjects allKeys] objectAtIndex:section];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"CellIdentifier"];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"CellIdentifier"];
}
//Get all the NSArray associated with this section, which will be an array of ProductObjects or an array of CategoryObjects
NSString *key = [[self.tableObjects allKeys] objectAtIndex:indexPath.section];
NSArray *sectionobjects = (NSArray*)[self.tableObjects objectForKey:key];
id object = [sectionobjects objectAtIndex:indexPath.row];
//Set the cell text based on what kind of object is returned
if ([object isKindOfClass:[ProductObject class]]) {
cell.textLabel.text = [(ProductObject*)object productTitle];
}
else if ([object isKindOfClass:[CategoryObject class]]) {
cell.textLabel.text = [(CategoryObject*)object categoryName];
}
return cell;
}
#pragma mark -
#pragma mark - UITableView delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSString *key = [[self.tableObjects allKeys] objectAtIndex:indexPath.section];
NSArray *sectionobjects = (NSArray*)[self.tableObjects objectForKey:key];
id object = [sectionobjects objectAtIndex:indexPath.row];
//They selected a product
if ([object isKindOfClass:[ProductObject class]]) {
ProductObject *product = (ProductObject*)object;
NSLog(#"%#", product.productTitle);
NSLog(#"%#", product.productCode);
NSLog(#"%#", product.productId);
}
//They selected a Category
else if ([object isKindOfClass:[CategoryObject class]]) {
//Check to see if the CategoryObject has any ProductObjects associated with it
if ([(CategoryObject*)object products]) {
//Now you will need to pass array of ProductObjects this along to your next view controller.
NSArray *cateogryProducts = [(CategoryObject*)object products];
//For demonstration purposes, i'll run through and print out all the Products for this Category
[cateogryProducts enumerateObjectsUsingBlock:^(ProductObject *product, NSUInteger idx, BOOL *stop) {
NSLog(#"%#", product.productTitle);
NSLog(#"%#", product.productCode);
NSLog(#"%#", product.productId);
}];
}
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//Start parsing the JSON
[self parseJSON];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
EDIT:
If you are wanting to open and close parts of the table like an accordion, take a look at Apple's same code: Table View Animations and Gestures.

Memory keep increasing when the UITableView scrolling

there is a strange problem I have not met ever
there is an array() including some custom object named MyClass parsed by JSONKit;
when I keep scrolling the tableview the memory will keeping increasing too.
but when replace
cell.textLabel.text = myclass.name;
with
cell.textLabel.text = #"cool";
or
cell.textLabel.text = [NSString stringWithFormate:#"a-%d", indexPath.row];
it's ok the memory with keep stable
but if I use
cell.textLabel.text = [NSString stringWithFormate:#"a-%#-i",myclass.name, indexPath.row];
it also keep increasing;
It will drive my crazy!!
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier = #"Singers";
OMTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
MyClass *myclass = [self.data objectAtIndex:indexPath.row];
if (cell == nil){
cell = [[[OMTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] autorelease];
}
cell.textLabel.text = myclass.name;
return cell;
}
MyClass
there is two class one Base another inherit
Base:
#interface OMBase : NSObject {
NSMutableDictionary *data;
NSString *name;
NSArray *keys;
}
#property (nonatomic, retain) NSString *name;
#property (nonatomic, copy) NSMutableDictionary *data;
#implementation OMBase
#synthesize data, name;
- (void)setData:(NSMutableDictionary *)adata{
if (data){
[data release];
data = nil;
}
data = [adata mutableCopy];
}
- (void)dealloc{
if (keys){
[keys release];
}
[data release];
[super dealloc];
}
- (id)init{
if (self = [super init]){
self.data = [[[NSMutableDictionary alloc] initWithCapacity:20] autorelease];
}
return self;
}
inherit:
#import "OMBase.h"
#interface OMLyric : OMBase
- (NSString *)songid;
- (NSString *)content;
#import "OMLyric.h"
#implementation OMLyric
- (NSString *)songid{
return [data objectForKey:#"songid"];
}
- (NSString *)content{
return [data objectForKey:#"content"];
}
Seems like your myclass.name getter returns a new allocated object. We can't say more without seeing myclass.

Queue a NSMutableArray into a NString as a loop?

If one had a NSString that needed a userid to be used as a URL for a request:
And one had a NSMutableArray that he wanted to Queue into the above call one at a time? So basically make 3 calls of NSString from the NSMutableArray .
One can check multiple UITableView cells and once completed I can index which cell rows were pushed. That is what userIDArray is used for now I want to make a call with the userID's I got back from userIDArray.
for (NSDictionary* userIDDict in userIDArray)
{
userIDArray = [[NSMutableArray alloc] init]; //I put this line in my viewdidload
NSNumber* userID = [userIDDict objectForKey:#"UserID"];
}
UserIDArray is the NSMutableArray .
This would be the NSLog from the NSMutableArray The Integer would be 1, 2 and 3.
UserID: 1
UserID: 2
UserID: 3
So in other words I would like to take the results from my NSMultiTableArray 1,2 and 3 to use within the NSString :
NSString *userProfile = [NSString stringWithFormat:#"http://example.com/userid=1"];
NSString *userProfile = [NSString stringWithFormat:#"http://example.com/userid=2"];
NSString *userProfile = [NSString stringWithFormat:#"http://example.com/userid=3"];
So I would make the first call and wait for a result, and then the second and finally the third.
Can this be done? I have search this link about Queues and this one but I am unsure if those are what I need?
UserDetailViewController.h file:
#interface UserDetailViewController : UIViewController <UITableViewDelegate>{
long long expectedLength;
long long currentLength;
UITableView *userTableView;
NSIndexPath* checkedIndexPath;
}
#property (nonatomic, retain) NSArray *userIDJson;
#property (strong, nonatomic) NSDictionary *userIDDict;
#property (nonatomic, retain) NSIndexPath* checkedIndexPath;
#property (nonatomic, strong) NSMutableArray *userIDArray;
#property (nonatomic) NSInteger currentUserIndex;
#end
UserDetailViewController.m file:
#interface UserDetailViewController ()
#end
#implementation UserDetailViewController
#synthesize userIDJson;
#synthesize userIDDict;
#synthesize checkedIndexPath;
#synthesize userIDArray;
#synthesize currentUserIndex;
- (void)viewDidLoad
{
[super viewDidLoad];
userIDArray = [[NSMutableArray alloc] init];
[self.navigationController setNavigationBarHidden:NO];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//return self.loadedSearches.count;
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.userIDJson.count;
}
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] ;
}
cell.textLabel.text = self.userIDJson[indexPath.row][#"UserName"];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
if([self.checkedIndexPath isEqual:indexPath])
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *thisCell = [tableView cellForRowAtIndexPath:indexPath];
NSString *userStringIndex = [self.userIDJson objectAtIndex:indexPath.row];
if (thisCell.accessoryType == UITableViewCellAccessoryNone)
{
thisCell.accessoryType = UITableViewCellAccessoryCheckmark;
[userIDArray addObject:userStringIndex];
}
else
{
thisCell.accessoryType = UITableViewCellAccessoryNone;
[userIDArray removeObject:userStringIndex];
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
if (self.currentUserIndex < userIDArray.count) {
NSNumber* userID = [[userIDArray objectForIndex:currentUserIndex]objectForKey:#"UserID"];
//Make the actual request here, and assign the delegate.
NSString *userProfile = [NSString stringWithFormat:#"http://example.com/userid=%#",userID];
self.currentUserIndex++;
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:userProfile]];
NSString *userResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
NSURL *url = [[NSURL alloc] initWithString: userProfile];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
userIDJson = [NSJSONSerialization JSONObjectWithData:dataURL
options:kNilOptions
error:&error];
}
}
for (userIDDict in userIDArray)
{
NSNumber* userID = [userIDDict objectForKey:#"UserID"];
NSLog(#"%#", userID);
NSArray* userName = [userIDDict objectForKey:#"UserName"];
}
NSURLConnection can take a delegate through the constructor initWithRequest:delegate:. So you need the object that makes the calls conform to that protocol, I'll assume it's a UIViewController. You can use one of the required methods in the delegate to fire up the next request.
For example, assume you have property to indicate the current index.
#property (nonatomic) NSInteger currentUserIndex;
Then in the place that will fire the first request, make the call for the first user. In some delegate method, say connectionDidFinishLoading:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
if (self.currentUserIndex < self.userIDArray.count) {
NSNumber* userID = [[self.userIDArray objectAtIndex:self.currentUserIndex] objectForKey:#"UserID"];
self.currentUserIndex++;
//Make the actual request here, and assign the delegate.
}
}
Of course, if your connection calls don't have to be synchronous, you can do it in an easier way.

Resources