zoukankan      html  css  js  c++  java
  • objectiveC中如何判断一个类中有没有定义某个方法

    C#中可以通过反射分析元数据来解决这个问题,示例代码如下:
    using System;
    using System.Reflection;
    
    namespace Hello
    {
        class Program
        {
            static void Main(string[] args)
            {
                if (IsMethodDefined(typeof(Utils), "HelloWorld"))
                {
                    Console.WriteLine("Utils类中有方法HelloWorld");
                }
                else 
                {
                    Console.WriteLine("Utils类中没有方法HelloWorld");
                }
                Console.ReadKey();
            }     
           
            /// <summary>
            /// 判断一个类中有无"指定名称"的方法
            /// </summary>
            /// <param name="type"></param>
            /// <param name="methodName"></param>
            /// <returns></returns>
            static bool IsMethodDefined(Type type,string methodName) 
            {
                bool result = false;
                foreach (MemberInfo m in type.GetMembers())
                {
                    if (m.Name == methodName) 
                    {
                        result = true;
                        break;
                    }
                }
                return result;
            }
        }
    
        public static class Utils
        {
            public static void HelloWorld()
            {
                Console.WriteLine("Hello World!");
            }
        }
    }
    

    在obj-C中,则是通过选择器selector来判断的

    Sampe.h

    #import <Foundation/Foundation.h>
    
    @interface Sample : NSObject {
    
    }
    
    -(void) print:(NSString*) msg;
    
    @end
    

    Sample.m

    #import "Sample.h"
    
    @implementation Sample
    
    -(void) print:(NSString*) msg
    {
    	NSLog(@"%@",msg);
    }
    
    @end
    

    main函数:

    #import <Foundation/Foundation.h>
    #import "Sample.h"
    
    int main (int argc, const char * argv[]) {
        
    	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    	
    	Sample *s = [Sample new];	
    	
    	if ([s respondsToSelector:@selector(print:)]) //这一行就是判断实例s中有没有方法print
    	{
    		[s print:@"Hello World"];
    	}
    	else
    	{
    		NSLog(@"%@",@"Sample类中没有定义方法print");
    	}
    	
    	[s release];
    	
        [pool drain];
        return 0;
    }
    

    作者:菩提树下的杨过
    出处:http://yjmyzz.cnblogs.com
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    音频、摄像机操作
    调用系统相机及摄像机
    图片的放大缩小
    haxm intelx86加速模拟器的安装
    mac eclipse 下安装subclipse
    文件多线程下载实现
    windows与linux之间传输文件
    ZeroMQ接口函数之 :zmq_setsockopt –设置ZMQ socket的属性
    使用C语言在windows下一口气打开一批网页
    Net-SNMP是线程安全的吗
  • 原文地址:https://www.cnblogs.com/yjmyzz/p/1966944.html
Copyright © 2011-2022 走看看