Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse a NSArray worry? [closed]

I have the following code,how can i reverse the messages Array,see bellow:

#import "newsViewController.h"
#import "DetailViewController.h"

@implementation newsViewController

@synthesize messageList;

//##############################################################################################################################
//#################                           CUSTOM VIEW INITALIZATION                                      #################//
//##############################################################################################################################
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        lastId = 0;
        chatParser = NULL;
    }
    return self;
}

//##############################################################################################################################
//#################                           DEALLOC - MEMORY RELEASE                                       #################//
//##############################################################################################################################
-(void)dealloc {
    [messageList release];
    [super dealloc];
}

//##############################################################################################################################
//#################                           DISPLAY PHP FILE INTEGRATION                                   #################//
//##############################################################################################################################
-(void)getNewMessages {

    NSString *url = [NSString stringWithFormat:@"http://localhost/sportApp/messages.php?past=%ld&t=%ld",lastId, time(0) ];

    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
    [request setURL:[NSURL URLWithString:url]];
    [request setHTTPMethod:@"GET"];

    NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];  

    if (conn){  
        receivedData = [[NSMutableData data] retain];  
    }else{}  
}

//##############################################################################################################################
//#################                                FETCHING PRAGMAS                                          #################//
//##############################################################################################################################
-(void)timerCallback {
    [timer release];
    [self getNewMessages];
}

//##############################################################################################################################
//#################                             CONNECTION PRAGMAS                                           #################//
//##############################################################################################################################
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [receivedData setLength:0];
}  
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [receivedData appendData:data];
}  
-(void)connectionDidFinishLoading:(NSURLConnection *)connection  {  

    if (chatParser)
        [chatParser release];

    if (messages == nil)

        messages = [[NSMutableArray alloc] init];

    chatParser = [[NSXMLParser alloc] initWithData:receivedData];
    [chatParser setDelegate:self];
    [chatParser parse];

    [receivedData release];  
    [messageList reloadData];

    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector: @selector(timerCallback)]];
    //[invocation setTarget:self];
    [invocation setSelector:@selector(timerCallback)];
    timer = [NSTimer scheduledTimerWithTimeInterval:5.0 invocation:invocation repeats:NO];
}  

//##############################################################################################################################
//#################                         PARSING THE MESSAGE XML FILE LIST                                #################//
//##############################################################################################################################
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {

    if ( [elementName isEqualToString:@"message"] ) {

        msgAdded = [[attributeDict objectForKey:@"added"] retain];
        msgId = [[attributeDict objectForKey:@"id"] intValue];

        msgUser   = [[NSMutableString alloc] init];
        msgText   = [[NSMutableString alloc] init];
        msgText2  = [[NSMutableString alloc] init];
        msgImage  = [[NSMutableString alloc] init];
        msgVideo  = [[NSMutableString alloc] init];

        inUser   = NO;
        inText   = NO;
        inText2  = NO;
        inImage  = NO;
        inVideo  = NO;
    }
    if ( [elementName isEqualToString:@"user"] )     { inUser = YES;  }
    if ( [elementName isEqualToString:@"text"] )     { inText = YES;  }
    if ( [elementName isEqualToString:@"subtext"] )  { inText2 = YES; }
    if ( [elementName isEqualToString:@"image"] )    { inImage = YES; }
    if ( [elementName isEqualToString:@"ytvideo"] )  { inVideo = YES; }


}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {

    if ( inUser )  { [msgUser appendString:string]; }
    if ( inText )  { [msgText appendString:string]; }
    if ( inText2 )  { [msgText2 appendString:string]; }
    if ( inImage ) { [msgImage appendString:string];}
    if ( inVideo ) { [msgVideo appendString:string];}

}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {

    if ( [elementName isEqualToString:@"message"] ) {

        [messages addObject:[NSDictionary dictionaryWithObjectsAndKeys:msgAdded,@"added",msgUser,@"user",msgText,@"text",msgText2,@"subtext",msgImage,@"image",msgVideo,@"ytvideo",nil]];

        [[messages reverseObjectEnumerator] allObjects];

        lastId = msgId;

        [msgAdded release];
        [msgUser release];
        [msgText release];
        [msgText2 release];
        [msgImage release];
        [msgVideo release];

    }

    if ( [elementName isEqualToString:@"user"]   ) { inUser = NO;}
    if ( [elementName isEqualToString:@"text"]   ) { inText = NO;}
    if ( [elementName isEqualToString:@"subtext"]   ) { inText2 = NO;}
    if ( [elementName isEqualToString:@"image"]  ) { inImage = NO;}
    if ( [elementName isEqualToString:@"ytvideo"]) { inVideo = NO;}
}

//##############################################################################################################################
//#################                         PARSING FINISHED - START DISPLAYING                              #################//
//##############################################################################################################################
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
-(NSInteger)tableView:(UITableView *)myTableView numberOfRowsInSection:(NSInteger)section {
    return ( messages == nil ) ? 0 : [messages count];
}
-(UITableViewCell *)tableView:(UITableView *)myTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = (UITableViewCell *)[self.messageList dequeueReusableCellWithIdentifier:@"newsCustomCell"];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"newsCustomCell" owner:self options:nil];
        cell = (UITableViewCell *)[nib objectAtIndex:0];
    }

    NSDictionary *itemAtIndex = (NSDictionary *)[messages objectAtIndex:indexPath.row];
    UILabel *timeDate = (UILabel *)[cell viewWithTag:1];
    timeDate.text = [itemAtIndex objectForKey:@"added"];
    UILabel *userL = (UILabel *)[cell viewWithTag:2];
    userL.text = [itemAtIndex objectForKey:@"user"];
    UILabel *textL = (UILabel *)[cell viewWithTag:3];
    textL.text = [itemAtIndex objectForKey:@"text"];
    UILabel *textL2 = (UILabel *)[cell viewWithTag:4];
    textL2.text = [itemAtIndex objectForKey:@"subtext"];
    UILabel *imageL = (UILabel *)[cell viewWithTag:5];
    imageL.text = [itemAtIndex objectForKey:@"image"];
    UILabel *videoL = (UILabel *)[cell viewWithTag:6];
    videoL.text = [itemAtIndex objectForKey:@"ytvideo"];

    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    DetailViewController *dvController = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:[NSBundle mainBundle]];

    NSDictionary *itemAtIndex = (NSDictionary *)[messages objectAtIndex:indexPath.row];

    NSString *selectTime = [itemAtIndex objectForKey:@"added"];

    NSString *selectUser = [itemAtIndex objectForKey:@"user"];

    NSString *selectMessage = [itemAtIndex objectForKey:@"text"];

    NSString *selectMessage2 = [itemAtIndex objectForKey:@"subtext"];

    NSString *selectImage = [itemAtIndex objectForKey:@"image"];

    NSString *selectVideo = [itemAtIndex objectForKey:@"ytvideo"];

    dvController.selectedTime = selectTime;
    dvController.selectedUser = selectUser;
    dvController.selectedImage = selectImage;
    dvController.selectedMessage = selectMessage;
    dvController.selectedMessage2 = selectMessage2;
    dvController.selectedVideo = selectVideo;


    [self.navigationController pushViewController:dvController animated:YES];
    [dvController release];
    dvController = nil;
}

//##############################################################################################################################
//#################                         PARSING FINISHED - START DISPLAYING                              #################//
//##############################################################################################################################
-(void)viewDidLoad {    
    messageList.dataSource = self;
    messageList.delegate = self;

    //@@@@@@@@TRY
    [[messages reverseObjectEnumerator] allObjects];

    [self getNewMessages];
    [super viewDidLoad];

}



@end

I've already searched for reverse a NSArray but all methods didn't work for me,help please!

like image 918
Jamal Tyson Avatar asked Sep 17 '11 21:09

Jamal Tyson


People also ask

How do you reverse an NSArray?

You can reverse a NSArray by writing your own loop iterating from the end towards the beginning and using a second array to add the items in reverse order. Or you can simply use - (NSEnumerator *)reverseObjectEnumerator from the NSArray class.


3 Answers

The easiest way to do it is:

NSArray *reversed = [[yourArray reverseObjectEnumerator] allObjects];
like image 77
Niklas Berglund Avatar answered Nov 06 '22 16:11

Niklas Berglund


You need something like:

NSMutableArray* reversedMessages = [NSMutableArray arrayWithCapacity:[messages count]];
NSEnumerator*   reverseEnumerator = [messages reverseObjectEnumerator];
for (id object in reverseEnumerator)
{
    [reversedMessages addObject:Object];
}

You could then assign reversedMessages to messages or do whatever else you want with it.

like image 35
adpalumbo Avatar answered Nov 06 '22 16:11

adpalumbo


You can reverse the order of an NSArray like this:

- (NSArray *)reverseArray:(NSArray*)array {
    NSMutableArray *mArray = [NSMutableArray arrayWithCapacity:[array count]];
    NSEnumerator *enumerator = [array reverseObjectEnumerator];
    for (id element in enumerator) {
        [mArray addObject:element];
    }
    return mArray;
}
like image 32
Jumhyn Avatar answered Nov 06 '22 17:11

Jumhyn