j.doe j.doe - 4 days ago 5
Objective-C Question

Call Boolen function in another class

Having function in class A.

-(BOOL) hasInternet {
Reachability *reach = [Reachability reachabilityWithHostName:@"www.google.com"];
NetworkStatus internetStats = [reach currentReachabilityStatus];
if ( internetStats == NotReachable ) {
return NO;
}
return YES;
}


Want to call in Class B in with If.... else condition
New to Objective-C.

Answer

If I had enough rep to comment, I'd just leave one, but since I don't, I'll leave this as an answer.

In your header file, you'll need to declare that function so that it's visible to other classes, then just like Teja Nandamuri said, you'll call it with [classB hasInternet], but you'll need to make sure that you've created the classB object first.

If you want to be able to call that method without having to create an object, use the + symbol instead of the -.

Example:

// SomeClass.h
@interface SomeClass: NSObject

+ (BOOL) hasInternet;

@end  

// SomeClass.m
#import "SomeClass.h"

@implementation SomeClass
-(BOOL) hasInternet {
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.google.com"];
    NetworkStatus internetStats = [reach currentReachabilityStatus];
    if ( internetStats == NotReachable ) {
        return NO;
    }
    return YES;
 }

In this case, you would call the method just by doing BOOL internet = [SomeClass hasInternet];, if the method declaration in the header file has a - you'll need to do something like this:

SomeClass *classB = [[SomeClass alloc] init];  
BOOL internet = [classB hasInternet];