невозможно передать строку моему методу - PullRequest
0 голосов
/ 18 декабря 2011

У меня проблема с тем, чтобы заставить метод работать, и я совершенно сбит с толку.Я не могу передать строку в качестве переменной для моего метода.

Я вызываю функцию даже со строкой, в настоящее время переменная отсутствует.

     Engine *myEngine = [Engine sharedInstance];
 [myEngine getContentArrayFromEngine:@"zumbra"]; 

Мой метод

-(NSMutableArray*) getContentArrayFromEngine:(NSString *)catName{
NSMutableSet* categorieContent = [[NSMutableSet alloc] init];
NSLog(@"Catname:%@", catName);   
//some more code
}

Вывод NSLOG 2011-12-18 18: 49: 44.165 Zitate [77224: 15203] Catname: (ноль)

ПочемуcatName пусто ???

edit1: полный код ThirdViewController.m

 -(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
 UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
 NSString* myTempCatname;
 myTempCatname = cell.textLabel.text; 

//  NSLog(@"test select %@", myTempCatname);

DetailViewController *detailVC = [self.storyboard instantiateViewControllerWithIdentifier:@"detailzitat"];
[self.navigationController pushViewController:detailVC animated:YES];
 Engine *myEngine = [Engine sharedInstance];
 [myEngine getContentArrayFromEngine:myTempCatname]; 

}

и в движке.

-(NSMutableArray*) getContentArrayFromEngine:(NSString *)catName{
NSMutableSet* categorieContent = [[NSMutableSet alloc] init];
NSLog(@"Übergebener Catname:%@", catName);
//  catName=@"zumbra";

//     NSLog(@"Inhalt InhalteFromWeb:%@", InhalteFromWeb);
NSLog(@"Catname:%@", catName);


unsigned count = [InhalteFromWeb count];
while (count--) {
    NSLog(@"count %d %@", count, [[InhalteFromWeb objectAtIndex:count] objectForKey:CATEGORY]);
    if([[[InhalteFromWeb objectAtIndex:count] objectForKey:CATEGORY] isEqualToString:catName]) {
        [categorieContent addObject:[InhalteFromWeb objectAtIndex:count]];
  NSLog(@"Row %d has Content%@",count, [InhalteFromWeb objectAtIndex:count]);
    }   
}
NSLog(@"Inhalt Category:%@", categorieContent);
NSArray* tempAr = [[NSArray alloc] initWithArray:[categorieContent allObjects]];

return  [NSMutableArray arrayWithArray:tempAr];

}

EDIT2:

Хорошо, даже подсказка с catName не сработала.поэтому я немного изменил свой код.

У меня есть массив с категорией, заголовком, содержанием, автором, изображением для каждой строки

Я хотел бы сделать две вещи 1) получить уникальный список всех категорий (работает нормально)) 2) при нажатии на одну из этих категорий откройте detailView, покажите первый элемент этой категории, перейдите к предыдущему и следующему элементу в категории, проводя пальцем по экрану.

Для этого я собираюсь установить категорию, которую я выбрал. Первая попытка состояла в том, чтобы передать метод, который не работал.Теперь я установил категорию в своем engine.h и при отображении одного элемента вернул массив для этой категории.

но опять же значение категории не сохраняется.

ThirdViewController.h

#import <UIKit/UIKit.h>
#import "SecondViewController.h"


@interface ThirdViewController :  UIViewController<UITableViewDelegate, UITableViewDataSource> {
    NSMutableArray* CategoryList;
}

@property (nonatomic, retain) NSMutableArray* CategoryList;

@end

ThirdViewController.m

#import "ThirdViewController.h"
#import "engine.h"
#import "DetailViewController.h"

@implementation ThirdViewController
@synthesize CategoryList;


- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    Engine *myEngine = [Engine sharedInstance];
    CategoryList = [myEngine getCategories];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {


    return [CategoryList count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *CellIdentifier =@"Cell";
    UITableViewCell *cell = (UITableViewCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

        if(cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }


    cell.textLabel.text = [CategoryList objectAtIndex:indexPath.row];
    return cell;

}


 -(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
 UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
 NSString* myTempCatname;
 myTempCatname = cell.textLabel.text; 


DetailViewController *detailVC = [self.storyboard instantiateViewControllerWithIdentifier:@"detailzitat"];
[self.navigationController pushViewController:detailVC animated:YES];
 Engine *myEngine = [Engine sharedInstance];
 [myEngine setCategName:myTempCatname];
 NSLog(@"Aufruf %@", myTempCatname);
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


@end

DetailViewController.h

#import <UIKit/UIKit.h>
#import <MessageUI/MFMailComposeViewController.h>
#import "engine.h"

@interface DetailViewController : UIViewController<MFMailComposeViewControllerDelegate> {
IBOutlet UILabel *authorLabel;
IBOutlet UILabel *categoryLabel; 
IBOutlet UILabel *titleLabel;
IBOutlet UITextView *contentTextView;
NSString *authorText, *contentText, *categoryText, *titleText, *imageText, *catName;
NSMutableArray *contentArray;
}

@property (nonatomic, retain) IBOutlet UITextView *contentTextView;
@property (nonatomic, retain) IBOutlet UILabel *authorLabel;
@property (nonatomic, retain) IBOutlet UILabel *categoryLabel;
@property (nonatomic, retain) IBOutlet UILabel *titleLabel;
@property (nonatomic, retain) NSString  *authorText, *contentText, *categoryText, *titleText, *imageText, *catName;
@property (nonatomic, retain) NSMutableArray *contentArray;


-(IBAction)vorher:(id)sender;
-(IBAction)nachher:(id)sender;
@end

DetailViewController.m

#import "DetailViewController.h"

@implementation DetailViewController
@synthesize contentTextView;
@synthesize authorText, contentText, categoryText, titleText, imageText;
@synthesize authorLabel, categoryLabel, titleLabel;
@synthesize contentArray;
@synthesize catName;

int contentIndex;
int contentMax;

- (IBAction)swipeDetected:(UIGestureRecognizer *)sender {

    NSLog(@"Right Swipe detected");
}


-(IBAction) vorher:(id)sender {
NSLog(@"-----VORHER Button gedrückt-------");

if (contentIndex==0) {contentIndex=contentMax-1;}
else {contentIndex--;}

titleText = [[contentArray objectAtIndex:contentIndex] objectForKey:TITLE];
authorText= [[contentArray objectAtIndex:contentIndex] objectForKey:AUTHOR];
contentText= [[contentArray objectAtIndex:contentIndex] objectForKey:CONTENT];    
authorLabel.text=authorText;
titleLabel.text=titleText;
contentTextView.text=contentText;
}

-(IBAction) nachher:(id)sender {
NSLog(@"-----Nachher Button gedrückt-------");

if (contentIndex==contentMax-1) {contentIndex=0;}
else {contentIndex++;}

titleText = [[contentArray objectAtIndex:contentIndex] objectForKey:TITLE];
authorText= [[contentArray objectAtIndex:contentIndex] objectForKey:AUTHOR];
contentText= [[contentArray objectAtIndex:contentIndex] objectForKey:CONTENT]; 
authorLabel.text=authorText;
titleLabel.text=titleText;
contentTextView.text=contentText;
}


- (void)didReceiveMemoryWarning
{ 
    [super didReceiveMemoryWarning];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
[super viewDidLoad];
Engine *myEngine = [Engine sharedInstance];
contentArray = [myEngine getContentArrayFromEngine];
contentMax = [contentArray count];


UISwipeGestureRecognizer *swipeRecognizerRight = 
[[UISwipeGestureRecognizer alloc]
 initWithTarget:self 
 action:@selector(vorher:)];
swipeRecognizerRight.direction = UISwipeGestureRecognizerDirectionRight;
[self.view addGestureRecognizer:swipeRecognizerRight];

UISwipeGestureRecognizer *swipeRecognizerLeft = 
[[UISwipeGestureRecognizer alloc]
 initWithTarget:self 
 action:@selector(nachher:)];
swipeRecognizerLeft.direction = UISwipeGestureRecognizerDirectionLeft;
[self.view addGestureRecognizer:swipeRecognizerLeft];

titleText = [[contentArray objectAtIndex:contentIndex] objectForKey:TITLE];
authorText= [[contentArray objectAtIndex:contentIndex] objectForKey:AUTHOR];
contentText= [[contentArray objectAtIndex:contentIndex] objectForKey:CONTENT]; 
authorLabel.text=authorText;
titleLabel.text=titleText;
contentTextView.text=contentText;    
}


- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end

engine.h

//#import 

#define AUTHOR  @"author"
#define CATEGORY  @"cat"
#define CONTENT  @"content"
#define IMAGE @"image"
#define TITLE @"title"


@interface Engine : NSObject {
        NSMutableArray* InhalteFromWeb;
    NSInteger maxAnzahlInhalte;
    NSString* categNameStorage;
}

+ (Engine *) sharedInstance;

- (NSMutableArray*) getZitateArrayFromEngine;
- (NSInteger) getMaxAnzahlZitateFromEngine;

- (NSString*) getAutor:(NSInteger)pos;
- (NSString*) getZitat:(NSInteger)pos;

- (NSString*) getAuthor:(NSInteger)pos;
- (NSString*) getCategory:(NSInteger)pos;
- (NSString*) getContent:(NSInteger)pos;
- (NSString*) getImage:(NSInteger)pos;
- (NSString*) getTitle:(NSInteger)pos;

-(NSMutableArray*) getContentArrayFromEngine;
-(void) setCategName:(NSString *) categNameVariable;
-(NSString*) getCategName;

-(NSMutableArray*) getCategories;

@end

engine.m

#import "Engine.h"

@implementation Engine

static Engine *_sharedInstance;

- (id) init
{
    if (self = [super init])
    {
        // custom initialization

        //Beginn my code
        NSURL *url = [NSURL URLWithString:@"http://www.*/iMotivate.plist"];
        NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];

        NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

        if( theConnection )
        {

            InhalteFromWeb = [[NSMutableArray alloc] initWithContentsOfURL:url];
            maxAnzahlInhalte = [InhalteFromWeb count];
        }
        else
        {
            NSLog(@"Connection failed");
        }
    }
    return self;
}


-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
  //  NSLog(@"Recieving Response...");
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{

 //   NSLog(@"Recieving Data...");

}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
                                                   message : @"An error has occured.Please verify your internet connection."
                                                   delegate:nil
                                         cancelButtonTitle :@"OK"
                                         otherButtonTitles :nil];
    [alert show];



}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{

  //  NSLog(@"DONE. Received Quotes: %d", maxAnzahlZitate);
}




// ###########

+ (Engine *) sharedInstance
{
    if (!_sharedInstance)
    {
        _sharedInstance = [[Engine alloc] init];
    }

    return _sharedInstance;
}

// Getter and Setter for WebArray
- (NSMutableArray*) getZitateArrayFromEngine{
    return InhalteFromWeb;

}
- (NSInteger) getMaxAnzahlZitateFromEngine{
    return maxAnzahlInhalte;
}

- (NSString*) getAutor:(NSInteger)pos{
    return [[InhalteFromWeb objectAtIndex:pos] objectForKey:AUTHOR];

}
- (NSString*) getZitat:(NSInteger)pos{
    return [[InhalteFromWeb objectAtIndex:pos] objectForKey:CONTENT];
}

// #######

- (NSString*) getAuthor:(NSInteger)pos{
    return [[InhalteFromWeb objectAtIndex:pos] objectForKey:AUTHOR];

}

- (NSString*) getCategory:(NSInteger)pos{
    return [[InhalteFromWeb objectAtIndex:pos] objectForKey:CATEGORY];

}

- (NSString*) getContent:(NSInteger)pos{
    return [[InhalteFromWeb objectAtIndex:pos] objectForKey:CONTENT];

}

- (NSString*) getImage:(NSInteger)pos{
    return [[InhalteFromWeb objectAtIndex:pos] objectForKey:IMAGE];

}
- (NSString*) getTitle:(NSInteger)pos{
    return [[InhalteFromWeb objectAtIndex:pos] objectForKey:TITLE];

}

-(NSArray*) getCategories {
    NSMutableSet* categorieSet = [[NSMutableSet alloc] init];

    unsigned count = [InhalteFromWeb count];
    while (count--) {
        NSString *tempString;
        tempString=[[InhalteFromWeb objectAtIndex:count] objectForKey:CATEGORY];
  //      NSLog(@"tempString %@", tempString );

        [categorieSet addObject:tempString];
    }
 //   NSLog(@"categories from engine %@", categorieSet);
    NSArray* tempAr = [[[NSArray alloc] initWithArray:[categorieSet allObjects]]sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];

    return  [NSMutableArray arrayWithArray:tempAr];

}

-(void) setCategName:(NSString *) categNameVariable
{   NSLog(@"categNameStorage 2%@",categNameStorage);
    categNameStorage=categNameVariable;
    NSLog(@"setCategName 1 %@",categNameVariable);
    NSLog(@"categNameStorage 2%@",categNameStorage);
}

-(NSString*) getCategName {
    return categNameStorage;
}



-(NSMutableArray*) getContentArrayFromEngine{
    NSMutableSet* categorieContent = [[NSMutableSet alloc] init];
    NSLog(@"Übergebener Catname:%@", categNameStorage);  
   //     NSLog(@"Inhalt InhalteFromWeb:%@", InhalteFromWeb);


    unsigned count = [InhalteFromWeb count];
    while (count--) {
 //       NSLog(@"count %d %@", count, [[InhalteFromWeb objectAtIndex:count] objectForKey:CATEGORY]);
        if([[[InhalteFromWeb objectAtIndex:count] objectForKey:CATEGORY] isEqualToString:categNameStorage]) {
            [categorieContent addObject:[InhalteFromWeb objectAtIndex:count]];
 //     NSLog(@"Row %d has Content%@",count, [InhalteFromWeb objectAtIndex:count]);
        }   
    }
 //   NSLog(@"Inhalt Category:%@", categorieContent);
    NSArray* tempAr = [[NSArray alloc] initWithArray:[categorieContent allObjects]];

    return  [NSMutableArray arrayWithArray:tempAr];
}


@end

1 Ответ

0 голосов
/ 19 декабря 2011

Должен быть конфликт переменных с 'catName' в вашем контроллере представления. Я не уверен, почему контроллер представления находится в области видимости, но держу пари, что если вы измените свой параметр на «inCatName», все будет хорошо. По этой причине хорошо использовать такие соглашения об именах.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...