Method cellForRowAtIndexPath method was not get called - xcode4

Am a beginner in iOS, am creating an application with the help of table view. I just run my application, while running the app, the app does not calling the method cellForRowIndexPath. Am using Json as web service. In the output screen, the parsing data is shown but it is not get display in simulator. i put breakpoint and i understood the cellForRowIndexPath path was not called. I drag datasourse and data delegate to files onner of xib file. but nothing is occurring... the table view is get displaying but there is no content... am screwed.. Any one please help me...
#implementation MSPackagesController
#synthesize packageTable;
#synthesize packages;
#synthesize mainCtrl;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
-(void)viewDidLoad
{
[super viewDidLoad];
}
-(void)parseData {
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.animationType = MBProgressHUDAnimationFade;
hud.detailsLabelText = #"Loading...";
MSJsonParser *parser = [[MSJsonParser alloc]initWithParserType:kPackagesParsing];
parser._parserSource = self;
[parser requestParsingWithUrl:PACKAGES_LIST_URL];
}
-(void)sharePackageFromCell:(UIButton*)btn
{
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.animationType = MBProgressHUDAnimationFade;
hud.detailsLabelText = #"Loading...";
NSString *title = [[self.packages objectAtIndex:btn.tag] packageName];
/*NSURL *imgUrl = [NSURL URLWithString:[[self.promotions objectAtIndex:btn.tag] picture]];
NSData *imgdata = [NSData dataWithContentsOfURL:imgUrl];
UIImage *image = [UIImage imageWithData:imgdata];*/
// NSURL *imgUrl = [NSURL URLWithString:[[self.packages objectAtIndex:btn.tag] picture]];
NSString *desc = [[self.packages objectAtIndex:btn.tag] packageDescription];
NSString *message = #"Visit GlamZapp in AppStore";
UIActivityViewController *activityCtrl = [[UIActivityViewController alloc]initWithActivityItems:[NSArray arrayWithObjects:title,desc,message, nil] applicationActivities:nil];
activityCtrl.excludedActivityTypes = #[UIActivityTypePrint,UIActivityTypePostToWeibo,UIActivityTypeMessage,UIActivityTypeAssignToContact];
activityCtrl.completionHandler = ^(NSString *activityType, BOOL completed)
{
NSLog(#" activityType: %#", activityType);
NSLog(#" completed: %i", completed);
};
[self.mainCtrl presentViewController:activityCtrl animated:YES completion:^{
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [packages count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
MSPackagesCell *cell = (MSPackagesCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *cells = [[NSBundle mainBundle]loadNibNamed:[Common checkDeviceforController:#"MSPackagesCell"] owner:nil options:nil];
for (id eachObject in cells) {
cell = eachObject;
break;
}
//cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
// Configure the cell...
// NSURL *imgUrl = [NSURL URLWithString:[[self.promotions objectAtIndex:indexPath.row]picture]];
//[cell.promoImg setImageWithURL:imgUrl placeholderImage:[UIImage imageNamed:#"slider_dummy.jpg"] andSize:cell.promoImg.frame.size];
cell.PackageName.text = [[self.packages objectAtIndex:indexPath.row] packageName];
cell.PackageDescription.text = [[self.packages objectAtIndex:indexPath.row] packageDescription];
// NSMutableAttributedString *strikedPrice = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:#"%# %#",CURRENCY_UNIT,[[self.packages objectAtIndex:indexPath.row] packageAmount] ] ];
// [strikedPrice addAttribute:NSStrikethroughStyleAttributeName value:[NSNumber numberWithInt:2] range:NSMakeRange(0, [strikedPrice length])];
//cell.oldPriceLabel.attributedText = strikedPrice;
cell.PriceLabel.text = [NSString stringWithFormat:#"%# %#",CURRENCY_UNIT,[[self.packages objectAtIndex:indexPath.row] packageAmount] ];
//[string appendFormat:#"%#\r\n", message];
// cell.promocodelabel.text = [NSString stringWithFormat:#"Promo code: %#",[[self.packages objectAtIndex:indexPath.row] promoCode]];
cell.ShareButton.tag = indexPath.row;
[cell.ShareButton addTarget:self action:#selector(sharePackageFromCell:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// MSPackageDetailsController *promDet = [[MSPackageDetailsController alloc]initWithNibName:[Common checkDeviceforController:#"MSPackageDetailsController"] bundle:nil];
// promDet.delegate = self;
// promDet.offerId = [[self.packages objectAtIndex:indexPath.row] promoId];
// promDet.title = [[self.packages objectAtIndex:indexPath.row] promoTitle];
// [self.delegate didSelectPromotion:promDet];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
-(void)foundPackagesData:(NSArray *)packa
{
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
self.packages = packa;
[self.packageTable reloadData];
}
-(void)connectionFailed
{
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}

I think you have not added UITableviewDataSource and UITableViewDelegate in your .h file

Add UITableViewDataSource,UITableViewDelegate in interface (.h) file
#interface MSPackagesController : UIViewController <UITableViewDataSource,UITableViewDelegate>

Related

Combining a TabBar and Navigation Controller IOS8

I'm new to iOS and I have troubles to display a navigation controller in my taBbar after Xcode 6 update.
With Xcode 5, it was working perfectly but now on the simulator I get an error message "Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Pushing a navigation controller is not supported'" and the app crashes.
Here is my code:
**appDelegate.m**
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:
(NSDictionary *)launchOptions{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor =[UIColor whiteColor];
[self.window makeKeyAndVisible];
*// tabBar items*
ItemUnViewController *itemUnViewController = [[ItemUnViewController alloc]
initWithNibName:nil
bundle:NULL];
ItemDeuxViewController *itemDeuxViewController = [[ItemDeuxViewController alloc]
initWithNibName:nil
bundle:NULL];
*//tabBar*
UITabBarController *tabBarController = [[UITabBarController alloc] init];
[tabBarController setViewControllers:#[itemUnViewController,itemDeuxViewController]];
*//setting tabBar as rootView*
self.window.rootViewController = tabBarController;
*// navigation Controllers*
UINavigationController *itemUnNavigationController =
[[UINavigationController alloc]
initWithRootViewController:itemUnViewController];
UINavigationController *itemDeuxNavigationController =
[[UINavigationController alloc]
initWithRootViewController:itemDeuxViewController];
*//Combining tabBar and Navigation Controllers*
[tabBarController setViewControllers:#
[itemUnNavigationController,itemDeuxNavigationController]];
return YES;
}
I even tried this way http://blog.rifkilabs.net/exploring-navigation-controller-and-tab-bar-controller.html but i get the same error message.
Thanks for your help.
tabBar_Controller = [[UITabBarController alloc]init];
[tabBar_Controller setDelegate:self];
ViewController1 *obj_1 = [obj_story instantiateViewControllerWithIdentifier:#"VC1"];
UINavigationController *navi_vc1 = [[UINavigationController alloc]initWithRootViewController:obj_1];
navi_vc1.navigationBarHidden = YES;
ViewController2 *obj_2 = [obj_story instantiateViewControllerWithIdentifier:#"VC2"];
UINavigationController *navi_vc2 = [[UINavigationController alloc]initWithRootViewController:obj_2];
navi_vc2.navigationBarHidden = YES;
[tabBar_Controller setViewControllers:[NSArray arrayWithObjects:navi_vc1,navi_vc2,nil]];
//Hide Tabbar View Controller.//
[self hideTabBar]
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
-(void) hideTabBar
{
for(UIView *view in tabBar_Controller.view.subviews)
{
if([view isKindOfClass:[UITabBar class]])
{
[view setFrame:CGRectMake(view.frame.origin.x, [UIScreen mainScreen].bounds.size.height, view.frame.size.width, view.frame.size.height)];
}
else
{
[view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, [UIScreen mainScreen].bounds.size.height)];
}
}
}
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
-(void)create_BottomBarButton
{
UIView *viewBottom = (UIView *)[self.window viewWithTag:Tag_BottomView];
if (viewBottom == nil)
{
#try
{
viewBottom = [[UIView alloc]init];
[viewBottom setFrame:CGRectMake([UIScreen mainScreen].bounds.origin.x, [UIScreen mainScreen].bounds.size.height-(HeightOfBottomBar+KsubviewHeight), [UIScreen mainScreen].bounds.size.width, HeightOfBottomBar)];
[viewBottom setBackgroundColor:RGB(47.0, 45.0, 45.0, 1.0)];
[viewBottom setTag:Tag_BottomView];
NSArray *arrImage = [NSLocalizedString(#"arrBottomBarImgs", nil)componentsSeparatedByString:#","];
float x = 0.0;
for (int i =0; i < kTotalTab; i++) {
[self create_TabBtn:viewBottom frame:CGRectMake(x, 0, 62,62) withTag:i+1 withImage:[arrImage objectAtIndex:i]];
x += 64.5;
}
[self.window addSubview:viewBottom];
}
#catch (NSException *exception)
{
NSLog(#"EXCEPTON %#",[exception description]);
}
}
}
-==-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-
-(void)select_Tab:(UIButton *)btn
{
#try {
[[tabBar_Controller.viewControllers objectAtIndex:btn.tag-1] popToRootViewControllerAnimated:YES];
[tabBar_Controller setSelectedIndex:btn.tag-1];
}
#catch (NSException *exception) {
NSLog(#"%s",__PRETTY_FUNCTION__);
}
}
-=-=-=-=-=-=-=-=-=-=-=-=-=-
-(void)pushTabBarIntoNavigationBar
{
[navi setNavigationBarHidden:YES];
[[UIApplication sharedApplication] setStatusBarHidden:NO];
[navi pushViewController:tabBar_Controller animated:YES];
}
-=-=-=-=-=-=-=-=-=-=-=
navi = [[UINavigationController alloc]initWithRootViewController:tabBar_Controller];
[navi setNavigationBarHidden:YES];
self.window.rootViewController = navi;

SQlite Database ios UITableView

I Have Change the Whole Database...
Now I Have Two Tables that Display Below
First Table:- Category Table
Cat_id CategoryName
====================================
1 Jesus
2 Buddha
3 BillGates
Second Table :- SayingTable
Say_id Cat_id Sayings
===================================
1 1 Never Say False
2 1 God Bless you
3 1 Be a Good Boy
4 2 Make a Peaceful World
5 2 Never Lie with the People
and I Have Used UITableView in My Firstview Controller
That Display Like Below Image
When i Click on Jesus Christ Cell..Or any Other cell then it Crash..
My Code is Below
FirstViewController.m
- (void)viewDidLoad
{
dataaray = [[NSMutableArray alloc] init];;
[dataaray addObject:#"Jesus Christ"];
[dataaray addObject:#"Budhdha"];
[dataaray addObject:#"BillGates"];
jesus = [[NSMutableArray alloc] init];
Buddha = [DatabaseOperation SelectCategory:2];
Buddha = [Buddha valueForKey:#"Saying"];
NSLog(#"Buddha Bhagwan Category=%#",Buddha);
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.dataaray count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *identifier = #"Cellidentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell==nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
cell.textLabel.text = [dataaray objectAtIndex:indexPath.row];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
DetailViewController *mydetail = [[DetailViewController alloc] initWithNibName:#"DetailViewController" bundle:nil];
if ([[dataaray objectAtIndex:indexPath.row] isEqual:#"Jesus Christ"])
{
mydetail.flag=1;
int SelectedRow = (indexpath.row+1);
jesus = [DatabaseOperation SelectCategory:SelectedRow];
jesus = [jesus valueForKey:#"Saying"];
NSLog(#"Jesus Category===%#",jesus);
mydetail.Jesus2Array = [jesus mutablecopy]; //Note Jesus2 is an Array of detailviewcontroller
}
else if ([[dataaray objectAtIndex:indexPath.row] isEqualToString:#"Budhdha"])
{
mydetail.flag=2;
SelectedRow = (indexpath.row+1);
Buddha = [DatabaseOperation SelectCategory:SelectedRow];
jesus = [jesus valueForKey:#"Saying"];
NSLog(#"Jesus Category===%#",jesus);
mydetail.Buddha2Array = [Buddha mutableCopy]; //Note Jesus2 is an Array of detailviewcontroller
}
DetailviewController.m
- (void)viewDidLoad
{
NSLog(#"Flag Value===%d",flag);
NSLog(#"Jesus 2 Array===%#",Jesus2Array);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (flag==1)
{
return [Jesus2Array count];
}
if(flag==2)
{
return [Buddha2array 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] autorelease];
if (flag==1)
{
cell.textLabel.text = [Jesus2Array objectAtIndex:indexPath.row];
}
DatabaseOperation.h
#import <Foundation/Foundation.h>
#import "DatabaseOperation.h"
#import <sqlite3.h>
#interface DatabaseOperation : NSObject
{
}
+(void)Check_Create_Database;
+(NSMutableArray*)SelectCategory:(int)Category_id;
DatabaseOperation.m
#import "DatabaseOperation.h"
#import <sqlite3.h>
static NSString *dbPath;
static NSString *databaseName=#"Message.sqlite";
#implementation DatabaseOperation
+(void)Check_Create_Database
{
dbPath =[[NSHomeDirectory() stringByAppendingPathComponent:#"Documents"] stringByAppendingPathComponent:databaseName];
BOOL success;
NSFileManager *fm=[NSFileManager defaultManager];
success=[fm fileExistsAtPath:dbPath];
if(success){
return;
}
NSString *dbPathFromApp=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
NSLog(#"dbPathFromApp = %#",dbPathFromApp);
[fm copyItemAtPath:dbPathFromApp toPath:dbPath error:nil];
}
+(NSMutableArray*)SelectCategory:(int)Category_id
//+(NSMutableArray*)SelectedCategory
{
sqlite3 *database;
NSMutableArray *dic=[[NSMutableArray alloc] init];
NSString *SAYING;
if(sqlite3_open([dbPath UTF8String] , &database) == SQLITE_OK)
{
NSString *sqlTmp=[NSString stringWithFormat:#"Select * from SayingTable Where Cat_id=%d",Category_id];
const char *sqlStmt=[sqlTmp UTF8String];
sqlite3_stmt *cmp_sqlStmt;
if(sqlite3_prepare_v2(database, sqlStmt, -1, &cmp_sqlStmt, NULL)==SQLITE_OK)
{
while(sqlite3_step(cmp_sqlStmt)==SQLITE_ROW)
{
NSLog(#"SQL Statements====%s",sqlStmt);
SAYING=[NSString stringWithUTF8String:(char *) sqlite3_column_text(cmp_sqlStmt, 2)];
NSMutableDictionary *dicObj=[[NSMutableDictionary alloc] init];
[dicObj setValue:[NSString stringWithFormat:#"%#",SAYING] forKey:#"Saying"];
[dic addObject: dicObj];
}
}
sqlite3_finalize(cmp_sqlStmt);
}
sqlite3_close(database);
When I Click the Cell then Detailview Controller is Not Loading.....i don't know whats Wrong in my Code Please Help..
Thank You...

ASIHTTPRequest backed RestKit object mapping

We must support some old code that runs using ASIHTTPRequest, but we want the object mapping and core data support provided by RestKit. Does anyone know of any way of "gluing" these two together?
I picture using ASIHTTPRequest for the requests and someone manually forwarding the payload over to RestKit.
Ok, so this wasn't too hard after all. Here is a class I wrote just for this (no disclaimers, it works for us and may be useful for someone else). You can use this as a direct replacement to the standard RKObjectLoader class.
.h file
#import <RestKit/RestKit.h>
#import "ASIFormDataRequest.h"
#interface ASIHTTPObjectLoader : ASIFormDataRequest <RKObjectMapperDelegate> {
RKObjectManager* _objectManager;
RKObjectMapping* _objectMapping;
RKObjectMappingResult* _result;
RKObjectMapping* _serializationMapping;
NSString* _serializationMIMEType;
NSObject* _sourceObject;
NSObject* _targetObject;
}
#property (nonatomic, retain) RKObjectMapping* objectMapping;
#property (nonatomic, readonly) RKObjectManager* objectManager;
#property (nonatomic, readonly) RKObjectMappingResult* result;
#property (nonatomic, retain) RKObjectMapping* serializationMapping;
#property (nonatomic, retain) NSString* serializationMIMEType;
#property (nonatomic, retain) NSObject* sourceObject;
#property (nonatomic, retain) NSObject* targetObject;
- (void) setDelegate:(id<RKObjectLoaderDelegate>)delegate;
+ (id)loaderWithResourcePath:(NSString*)resourcePath objectManager: (RKObjectManager*)objectManager delegate:(id<RKObjectLoaderDelegate>)delegate;
- (id)initWithResourcePath:(NSString*)resourcePath objectManager:(RKObjectManager*)objectManager delegate:(id<RKObjectLoaderDelegate>)delegate;
- (void)handleResponseError;
#end
.m file
#import "ASIHTTPObjectLoader.h"
#interface ASIFormDataRequest (here)
- (void) reportFailure;
- (void) reportFinished;
#end
#implementation ASIHTTPObjectLoader
#synthesize objectManager = _objectManager;
#synthesize targetObject = _targetObject, objectMapping = _objectMapping;
#synthesize result = _result;
#synthesize serializationMapping = _serializationMapping;
#synthesize serializationMIMEType = _serializationMIMEType;
#synthesize sourceObject = _sourceObject;
- (void) setDelegate:(id<RKObjectLoaderDelegate>)_delegate {
[super setDelegate: _delegate];
}
+ (id)loaderWithResourcePath:(NSString*)resourcePath objectManager:(RKObjectManager*)objectManager delegate:(id<RKObjectLoaderDelegate>)_delegate {
return [[[self alloc] initWithResourcePath:resourcePath objectManager:objectManager delegate:_delegate] autorelease];
}
- (id)initWithResourcePath:(NSString*)resourcePath objectManager:(RKObjectManager*)objectManager delegate:(id<RKObjectLoaderDelegate>)_delegate {
self = [super initWithURL: [objectManager.client URLForResourcePath: resourcePath]];
if ( self ) {
self.delegate = _delegate;
_objectManager = objectManager;
}
return self;
}
- (void)dealloc {
// Weak reference
_objectManager = nil;
[_sourceObject release];
_sourceObject = nil;
[_targetObject release];
_targetObject = nil;
[_objectMapping release];
_objectMapping = nil;
[_result release];
_result = nil;
[_serializationMIMEType release];
[_serializationMapping release];
[super dealloc];
}
- (void) reset {
[_result release];
_result = nil;
}
- (void)finalizeLoad:(BOOL)successful error:(NSError*)_error {
//_isLoading = NO;
if (successful) {
//_isLoaded = YES;
if ([self.delegate respondsToSelector:#selector(objectLoaderDidFinishLoading:)]) {
[self.delegate performSelectorOnMainThread:#selector(objectLoaderDidFinishLoading:)
withObject:self waitUntilDone:YES];
}
[super reportFinished];
/*
NSDictionary* userInfo = [NSDictionary dictionaryWithObject:_response
forKey:RKRequestDidLoadResponseNotificationUserInfoResponseKey];
[[NSNotificationCenter defaultCenter] postNotificationName:RKRequestDidLoadResponseNotification
object:self
userInfo:userInfo];
*/
} else {
NSDictionary* _userInfo = [NSDictionary dictionaryWithObject:(_error ? _error : (NSError*)[NSNull null])
forKey:RKRequestDidFailWithErrorNotificationUserInfoErrorKey];
[[NSNotificationCenter defaultCenter] postNotificationName:RKRequestDidFailWithErrorNotification
object:self
userInfo:_userInfo];
}
}
// Invoked on the main thread. Inform the delegate.
- (void)informDelegateOfObjectLoadWithResultDictionary:(NSDictionary*)resultDictionary {
NSAssert([NSThread isMainThread], #"RKObjectLoaderDelegate callbacks must occur on the main thread");
RKObjectMappingResult* result = [RKObjectMappingResult mappingResultWithDictionary:resultDictionary];
if ([self.delegate respondsToSelector:#selector(objectLoader:didLoadObjectDictionary:)]) {
[self.delegate objectLoader: (RKObjectLoader*)self didLoadObjectDictionary:[result asDictionary]];
}
if ([self.delegate respondsToSelector:#selector(objectLoader:didLoadObjects:)]) {
[self.delegate objectLoader: (RKObjectLoader*)self didLoadObjects:[result asCollection]];
}
if ([self.delegate respondsToSelector:#selector(objectLoader:didLoadObject:)]) {
[self.delegate objectLoader: (RKObjectLoader*)self didLoadObject:[result asObject]];
}
[self finalizeLoad:YES error:nil];
}
#pragma mark - Subclass Hooks
/**
Overloaded by ASIHTTPManagedObjectLoader to serialize/deserialize managed objects
at thread boundaries.
#protected
*/
- (void)processMappingResult:(RKObjectMappingResult*)result {
NSAssert(isSynchronous || ![NSThread isMainThread], #"Mapping result processing should occur on a background thread");
[self performSelectorOnMainThread:#selector(informDelegateOfObjectLoadWithResultDictionary:) withObject:[result asDictionary] waitUntilDone:YES];
}
#pragma mark - Response Object Mapping
- (RKObjectMappingResult*)mapResponseWithMappingProvider:(RKObjectMappingProvider*)mappingProvider toObject:(id)targetObject error:(NSError**)_error {
NSString* MIMEType = [[self responseHeaders] objectForKey: #"Content-Type"];
id<RKParser> parser = [[RKParserRegistry sharedRegistry] parserForMIMEType: MIMEType];
NSAssert1(parser, #"Cannot perform object load without a parser for MIME Type '%#'", MIMEType);
// Check that there is actually content in the response body for mapping. It is possible to get back a 200 response
// with the appropriate MIME Type with no content (such as for a successful PUT or DELETE). Make sure we don't generate an error
// in these cases
id bodyAsString = [self responseString];
if (bodyAsString == nil || [[bodyAsString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0) {
RKLogDebug(#"Mapping attempted on empty response body...");
if (self.targetObject) {
return [RKObjectMappingResult mappingResultWithDictionary:[NSDictionary dictionaryWithObject:self.targetObject forKey:#""]];
}
return [RKObjectMappingResult mappingResultWithDictionary:[NSDictionary dictionary]];
}
id parsedData = [parser objectFromString:bodyAsString error:_error];
if (parsedData == nil && _error) {
return nil;
}
// Allow the delegate to manipulate the data
if ([self.delegate respondsToSelector:#selector(objectLoader:willMapData:)]) {
parsedData = [[parsedData mutableCopy] autorelease];
[self.delegate objectLoader: (RKObjectLoader*)self willMapData:&parsedData];
}
RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:parsedData mappingProvider:mappingProvider];
mapper.targetObject = targetObject;
mapper.delegate = self;
RKObjectMappingResult* result = [mapper performMapping];
// Log any mapping errors
if (mapper.errorCount > 0) {
RKLogError(#"Encountered errors during mapping: %#", [[mapper.errors valueForKey:#"localizedDescription"] componentsJoinedByString:#", "]);
}
// The object mapper will return a nil result if mapping failed
if (nil == result) {
// TODO: Construct a composite error that wraps up all the other errors. Should probably make it performMapping:&error when we have this?
if (_error) *_error = [mapper.errors lastObject];
return nil;
}
return result;
}
- (RKObjectMappingResult*)performMapping:(NSError**)_error {
NSAssert( isSynchronous || ![NSThread isMainThread], #"Mapping should occur on a background thread");
RKObjectMappingProvider* mappingProvider;
if (self.objectMapping) {
NSString* rootKeyPath = self.objectMapping.rootKeyPath ? self.objectMapping.rootKeyPath : #"";
RKLogDebug(#"Found directly configured object mapping, creating temporary mapping provider for keyPath %#", rootKeyPath);
mappingProvider = [[RKObjectMappingProvider new] autorelease];
[mappingProvider setMapping:self.objectMapping forKeyPath:rootKeyPath];
} else {
RKLogDebug(#"No object mapping provider, using mapping provider from parent object manager to perform KVC mapping");
mappingProvider = self.objectManager.mappingProvider;
}
return [self mapResponseWithMappingProvider:mappingProvider toObject:self.targetObject error:_error];
}
- (void)performMappingOnBackgroundThread {
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
NSError* _error = nil;
_result = [[self performMapping:&_error] retain];
NSAssert(_result || _error, #"Expected performMapping to return a mapping result or an error.");
if (self.result) {
[self processMappingResult:self.result];
} else if (_error) {
[self failWithError: _error];
}
[pool drain];
}
- (BOOL)canParseMIMEType:(NSString*)MIMEType {
if ([[RKParserRegistry sharedRegistry] parserForMIMEType: MIMEType]) {
return YES;
}
RKLogWarning(#"Unable to find parser for MIME Type '%#'", MIMEType);
return NO;
}
- (BOOL)isResponseMappable {
if ([self responseStatusCode] == 503) {
[[NSNotificationCenter defaultCenter] postNotificationName:RKServiceDidBecomeUnavailableNotification object:self];
}
NSString* MIMEType = [[self responseHeaders] objectForKey: #"Content-Type"];
if ( error ) {
[self.delegate objectLoader: (RKObjectLoader*)self didFailWithError: error];
[self finalizeLoad:NO error: error];
return NO;
} else if ([self responseStatusCode] == 204) {
// The No Content (204) response will never have a message body or a MIME Type. Invoke the delegate with self
[self informDelegateOfObjectLoadWithResultDictionary:[NSDictionary dictionaryWithObject:self forKey:#""]];
return NO;
} else if (NO == [self canParseMIMEType: MIMEType]) {
// We can't parse the response, it's unmappable regardless of the status code
RKLogWarning(#"Encountered unexpected response with status code: %ld (MIME Type: %#)", (long) [self responseStatusCode], MIMEType);
NSError* _error = [NSError errorWithDomain:RKRestKitErrorDomain code:RKObjectLoaderUnexpectedResponseError userInfo:nil];
if ([self.delegate respondsToSelector:#selector(objectLoaderDidLoadUnexpectedResponse:)]) {
[self.delegate objectLoaderDidLoadUnexpectedResponse: (RKObjectLoader*)self];
} else {
[self.delegate objectLoader: (RKObjectLoader*)self didFailWithError: _error];
}
// NOTE: We skip didFailLoadWithError: here so that we don't send the delegate
// conflicting messages around unexpected response and failure with error
[self finalizeLoad:NO error:_error];
return NO;
} else if (([self responseStatusCode] >= 400 && [self responseStatusCode] < 500) ||
([self responseStatusCode] >= 500 && [self responseStatusCode] < 600) ) {
// This is an error and we can map the MIME Type of the response
[self handleResponseError];
return NO;
}
return YES;
}
- (void)handleResponseError {
// Since we are mapping what we know to be an error response, we don't want to map the result back onto our
// target object
NSError* _error = nil;
RKObjectMappingResult* result = [self mapResponseWithMappingProvider:self.objectManager.mappingProvider toObject:nil error:&_error];
if (result) {
_error = [result asError];
} else {
RKLogError(#"Encountered an error while attempting to map server side errors from payload: %#", [_error localizedDescription]);
}
[self.delegate objectLoader: (RKObjectLoader*)self didFailWithError:_error];
[self finalizeLoad:NO error:_error];
}
#pragma mark - RKRequest & RKRequestDelegate methods
- (void) reportFailure {
[self.delegate objectLoader: (RKObjectLoader*)self didFailWithError:error];
[super reportFailure];
}
- (void)reportFinished {
NSAssert([NSThread isMainThread], #"RKObjectLoaderDelegate callbacks must occur on the main thread");
if ([self isResponseMappable]) {
// Determine if we are synchronous here or not.
if (isSynchronous) {
NSError* _error = nil;
_result = [[self performMapping:&_error] retain];
if (self.result) {
[self processMappingResult:self.result];
} else {
[self performSelectorInBackground:#selector(failWithError:) withObject:_error];
}
[super reportFinished];
} else {
[self performSelectorInBackground:#selector(performMappingOnBackgroundThread) withObject:nil];
}
}
}
I do the following in my unit test code to make sure my object mappings are working
NSDictionary *headers = [NSDictionary dictionaryWithObjectsAndKeys:#"application/json", #"X-RESTKIT-CACHED-MIME-TYPE",
#"200", #"X-RESTKIT-CACHED-RESPONSE-CODE",
#"application/json; charset=utf-8", #"Content-Type",
nil];
NSURL *url = [[NSURL alloc] initWithString:#""]; //need a url to create a dummy RKRequest
RKRequest *request = [RKRequest requestWithURL:url];
[url release];
//Create a dummy response with the data payload
RKResponse *response = [[[RKResponse alloc] initWithRequest:request
body:myData //myData is NSData loaded from my file on disk in this case
headers:headers] autorelease];
RKURL *rkURL = [[RKURL alloc] initWithString:#"https://api.twitter.com"];
RKManagedObjectLoader *loader = [[RKManagedObjectLoader alloc] initWithURL:rkURL
mappingProvider:self.objectManager.mappingProvider
objectStore:self.objectManager.objectStore];
loader.delegate = self;
loader.objectMapping = self.objectMapping; //I pass the object mapping to use here.
[loader didFinishLoad:response]; //Given a response and request, Restkit will parse the response and call the usual delegates
You might be able to do somthing similar as well to grab the response data from ASIHTTPRequest and pass it on to RestKit

UITableView not populating with SQLite

I want to create a to-do list with SQLite, and I have been following this tutorial: http://klanguedoc.hubpages.com/hub/IOS-5-How-To-Display-SQLite-Data-in-a-UITableView
but it's not working! The simulator runs, and the app opens, but the table is blank. Am I doing something wrong? I am using xcode 4.2 for snow leopard.
In the .sqlite file I have a string text, integer priority, and boolean complete. However, I've just implemented "text" to make things simpler.
Here's my code:
// Title.h
#import <Foundation/Foundation.h>
#interface Title : NSObject {
NSString *text;
}
#property(nonatomic,copy) NSString *text;
#end
//TitleVC.h
#import <UIKit/UIKit.h>
#import <sqlite3.h>
#interface TitleVC : UITableViewController{
NSMutableArray *thelist;
sqlite3 *db;
}
#property (nonatomic,retain) NSMutableArray *thelist;
-(NSMutableArray *) toDo;
#end
//TitleVC.m
#import "TitleVC.h"
#import "Title.h"
#import <sqlite3.h>
#implementation TitleVC
#synthesize thelist;
- (void)viewDidLoad
{
[self toDo];
[super viewDidLoad];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [self.thelist count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"TitleCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
int rowCount = indexPath.row;
Title *title = [self.thelist objectAtIndex:rowCount];
cell.textLabel.text = title.text;
return cell;
}
-(NSMutableArray *) toDo{
thelist = [[NSMutableArray alloc] initWithCapacity:10];
#try{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"todo.sqlite"];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success)
{
NSLog(#"Cannot locate database file '%#'.",dbPath);
}
if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))
{
NSLog(#"An error has occured: %#",sqlite3_errmsg(db));
}
const char *sql = "SELECT * FROM todo";
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(#"Problem with prepare statement: %#", sqlite3_errmsg(db));
}else{
Title *title = [[Title alloc] init];
while (sqlite3_step(sqlStatement)==SQLITE_ROW){
title.text = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,1)];
[thelist addObject:title];
}
}
}
#catch (NSException *exception) {
NSLog(#"Problem with prepare statement: %#", sqlite3_errmsg(db));
}
#finally {
return thelist;
}
}
If you are using a standard UITableView, is tableView:numberOfRowsInSection: returning an appropriate value? What is tableView:cellForRowAtIndexPath: returning? I would put a break point in both locations and check to make that the methods are even being called.
Finally, if you are using a .xib file, is there a connection to the UITableView?

i had some images in resultstring i want to display it in tableview

i had some images in resultstring ,resultstring is what i get from the server ,it contains images ,i want that images and display it in tableview
my code is
viewdidload
{
NSString *urlVal = #"http://at.azinova.info/green4care/iphone/viewImage.php?id=";
NSString *urlVal1 = [urlVal stringByAppendingString:selectedCountryw];
NSURL *url1 = [NSURL URLWithString:urlVal1];
//NSURL *url1 = [NSURL URLWithString:urlVal];
NSString *resultString = [NSString stringWithContentsOfURL:url1 encoding:NSUTF8StringEncoding error:nil];
NSArray *arycountries1 = [resultString componentsSeparatedByString:#","];
UIAlertView *loginalert = [[UIAlertView alloc] initWithTitle:#" Message" message:resultString delegate:self
cancelButtonTitle:#"OK" otherButtonTitles:nil];
[loginalert show];
[loginalert release];
//arraycountries = [[NSArray alloc]initWitho:arycountries1];
arraycountries = [[NSArray alloc]initWithArray: arycountries1];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [arraycountries count];
}
// Customize the appearance of table view cells.
- (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] autorelease];
}
cell.imageView.image = [UIImage imageNamed:[arraycountries objectAtIndex:indexPath.row]];
// Configure the cell...
return cell;
}
please help
thankzzzzz
What you described is much like a message borad with images, there is a twitter open source project tweetero: http://code.google.com/p/tweetero/ You can take a look at MessageListController and ImageLoader.
In generally, you could do like this:
1) Send async request to server to get message date(not images)
2) reload the table data, and send the image loader request for each uiimageview.
3) set the uiimageview when the image is loaded. A default loading image can be used until the real image is loaded.

Resources